无法在渲染中访问 React redux 道具
React redux props cannot be accessed in render
我目前在显示 redux 状态树的一些结果时遇到问题。在我的控制台中,它显示当前对象在调用 this.props.walletStocks 后到达(存储在 redux 状态树中)。
然而,当我运行下面的代码时,它告诉我this.props.walletStocks['wallet4']是未定义的,因此还没有到达。
render() {
return(
{this.props.walletStocks['wallet4'].map((stock) => console.log(stock))}
);
}
我知道这是异步数据的问题,我真的不知道如何解决它。
提前致谢!
一个合适的解决方案是在启动异步数据请求时设置加载状态,并在异步数据加载完成后更新它(例如使用 Promise API)。然后使用该加载状态来确定呈现的内容。
在你的 redux 操作中的某处:
Promise.resolve()
.then(() => dispatch({
type: UPDATE_WALLET_STOCKS,
loading: true,
})
.then(fetch('https://YOU_API'))
.then(json => json.json())
.then(walletStocks => dispatch({
type: UPDATE_WALLET_STOCKS,
walletStocks,
loading: false,
});
也为您的组件提供加载状态,并在 YourComponent
渲染中基于该标志:
render() {
return(
{this.props.loading
? 'loading...'
: this.props.walletStocks['wallet4'].map((stock) => console.log(stock))}
);
}
}
您需要等待它加载然后显示。尝试检查一下。
render() {
return(
{this.props.walletStocks && this.props.walletStocks['wallet4'].map((stock) => console.log(stock))}
);
}
我目前在显示 redux 状态树的一些结果时遇到问题。在我的控制台中,它显示当前对象在调用 this.props.walletStocks 后到达(存储在 redux 状态树中)。
然而,当我运行下面的代码时,它告诉我this.props.walletStocks['wallet4']是未定义的,因此还没有到达。
render() {
return(
{this.props.walletStocks['wallet4'].map((stock) => console.log(stock))}
);
}
我知道这是异步数据的问题,我真的不知道如何解决它。
提前致谢!
一个合适的解决方案是在启动异步数据请求时设置加载状态,并在异步数据加载完成后更新它(例如使用 Promise API)。然后使用该加载状态来确定呈现的内容。
在你的 redux 操作中的某处:
Promise.resolve()
.then(() => dispatch({
type: UPDATE_WALLET_STOCKS,
loading: true,
})
.then(fetch('https://YOU_API'))
.then(json => json.json())
.then(walletStocks => dispatch({
type: UPDATE_WALLET_STOCKS,
walletStocks,
loading: false,
});
也为您的组件提供加载状态,并在 YourComponent
渲染中基于该标志:
render() {
return(
{this.props.loading
? 'loading...'
: this.props.walletStocks['wallet4'].map((stock) => console.log(stock))}
);
}
}
您需要等待它加载然后显示。尝试检查一下。
render() {
return(
{this.props.walletStocks && this.props.walletStocks['wallet4'].map((stock) => console.log(stock))}
);
}