2017-08-24 18 views
0

コンポーネントに小道具として渡されたIDを使用して製品オブジェクトを取得するためにAPI経由でデータをフェッチするReactコンポーネントがあります。エラーReact Reduxストアからのデータの取得と小道具へのマッピング

私はReact/Reduxアプリケーションを持っていて、私はReduxのフローがかなり新しいです。 私は、Action/Reducerを経由してストアにデータをロードするProducts(1つのProductオブジェクトを持つ配列)を持っています。

mapStateToPropsパターンを使用して、これをstateからpropsに渡そうとしています。

それは{ this.props.product.title }

Uncaught TypeError: Cannot read property '__reactInternalInstance$z9gkwvwuolc' of null 

をレンダリングされたときに、私は次のエラーを取得しています私はそれが非同期thatsのデータであることにその原因を考えます。 これを解決する最も良い方法は何ですか?以下は

は私のコードです -

class ProductListItem extends Component { 
    componentDidMount() { 
    this.props.dispatch(fetchProduct(this.props.id)); 
    } 

    render() { 
    return (
     <div> 
     <h1>{ this.props.product.title }</h1> 
     </div> 
    ); 
    } 
} 

// Actions required to provide data for this component to render in sever side. 
ProductListItem.need = [() => { return fetchProduct(this.props.id); }]; 

// Retrieve data from store as props 
function mapStateToProps(state, props) { 
    return { 
    product: state.products.data[0], 
    }; 
} 

ProductListItem.propTypes = { 
    id: PropTypes.string.isRequired, 
    dispatch: PropTypes.func.isRequired, 
    overlay: PropTypes.string, 
}; 

export default connect(mapStateToProps)(ProductListItem); 

答えて

1

あなたは製品が存在する場合、それが存在する場合にのみ、あなたが内部のデータにアクセスしますチェックする必要があります。この一般的なパターン:

class ProductListItem extends Component { 
    componentDidMount() { 
    this.props.dispatch(fetchProduct(this.props.id)); 
    } 

    render() { 
    const { product } = this.props; 
    return (
     <div> 
     { product && 
      <h1>{product.title}</h1> 
     } 
     </div> 
    ); 
    } 
} 

製品が存在する場合、コンポーネントは<h1>をレンダリングします。あなたのReduxのデフォルトの状態を定義することができる減速機で

+0

ああこれは私が行方不明だったものです!清潔なソリューション、ありがとう! – Yasir

0

は、デフォルトの状態を設定し、あなたはproduct.titleが未定義でない場合は、その製品をレンダリングし、

export default function reducer(state={ title : undefined}, action) { 

//ternary checking in render() on component 
product.title !== undefined ? product.title : undefined 

これは、チェックのいくつかの三元を行うことができます。タイトルは未定義です。

関連する問題