我有一个 React 组件,它通过 API 获取数据,以使用作为组件的 prop 传入的 ID 来检索产品对象。
我有一个 React / Redux 应用程序,而且我对 Redux 流程相当陌生。 我通过我的 Action/Reducer 将产品(具有一个产品对象的数组)数据加载到商店。
我正在尝试使用 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);
您需要检查产品是否存在,只有存在,您才会访问内部数据。这是一种常见的模式:
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减速器中,你可以定义默认状态,设置默认状态,然后你可以做一些三元检查
export default function reducer(state={ title : undefined}, action) {
//ternary checking in render() on component
product.title !== undefined ? product.title : undefined
这意味着,如果product.title不是未定义的,则渲染product.title,否则为未定义。