2017-08-24 39 views
0

我有一個React組件,它通過API獲取數據以通過使用作爲道具傳入組件的ID檢索產品對象。錯誤從React Redux Store檢索數據並映射到道具

我有一個React/Redux應用程序,我對Redux流程相當新。 我通過我的Action/Reducer將商品(具有一個Product對象的數組)加載到商店。

我想通過使用mapStateToProps模式從狀態傳遞給道具。

我收到以下錯誤,當它被渲染{ this.props.product.title }

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

我認爲它,由於它是多數民衆贊成異步數據。 解決這個問題的最佳方法是什麼?

下面是我的代碼 -

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>

+0

啊這是我失蹤了!清潔解決方案,謝謝! – Yasir

0

在你的終極版減速器可以定義默認狀態,設置默認狀態,然後你可以做一些檢查三元

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

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

這意味着,如果product.title不是不確定的,然後渲染產品。其他未定義的標題。

相關問題