【问题标题】:React redux props cannot be accessed in render在渲染中无法访问 React redux props
【发布时间】:2020-07-31 12:01:51
【问题描述】:

我目前在显示来自 redux 状态树的一些结果时遇到问题。在我的控制台中,它显示当前对象在调用 this.props.walletStocks 后已经到达(存储在 redux 状态树中)。

但是,当我运行以下代码时,它告诉我 this.props.walletStocks['wallet4'] 未定义,因此尚未到达。

render() {
    return(
       {this.props.walletStocks['wallet4'].map((stock) => console.log(stock))}
    );
}

我知道这是异步数据的问题,但我真的不知道如何解决。

提前致谢!

【问题讨论】:

  • 在迭代之前尝试检查错误值:this.props.walletStocks['wallet4'] && this.props.walletStocks['wallet4'].map(. . .)

标签: node.js reactjs redux react-redux react-props


【解决方案1】:

适当的解决方案是在启动异步数据请求时设置加载状态,并在异步数据加载完成后更新它(例如,使用 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))}
      );
    }
}

【讨论】:

    【解决方案2】:

    您需要等待它加载然后显示。试着检查一下。

    render() {
    return(
       {this.props.walletStocks && this.props.walletStocks['wallet4'].map((stock) => console.log(stock))}
    );
    

    }

    【讨论】:

    • 检查你的 mapStateToProps 函数可能吗?如果您没有将道具链接到状态怎么办?
    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 2020-01-09
    • 2018-10-24
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多