首页 > 解决方案 > 如何在 componentDidUpdate() 之后在 render() 中使用最新的 props?

问题描述

当我的组件挂载时,我调用一个 API 以通过 axios 在 redux 存储中获取人员列表。

componentDidMount() {
  this.props.getPeople();
}

基本上,一旦 API 调用成功,我将peopleList使用最新数据更新 redux 存储中的状态。

现在我映射这个peopleList(通过 mapStatetoProps)以在我的组件的render(). 到目前为止一切都很好。

但是,每个人卡都有一个“喜欢”按钮,该按钮反过来会发出 POST 请求以将人员对象的isLiked属性更改为“真”(并且还会使所有其他人员对象的'isLiked'属性为假(一次只能点赞一个) )。

现在,当我单击“喜欢”按钮时,它只会触发后端的更改。我必须刷新页面才能看到更新后的渲染 UI。

我是 React 的新手,我可以看到,当我执行 a 时componentDidUpdate(),我可以在单击“like”按钮时访问新数据,如下所示:

componentDidUpdate(prevProps) {

    if(this.props.people !== prevProps.people) {
        console.log("PREV");
        console.log(prevProps.people);
        console.log("LATEST");
        console.log(this.props.people);
    }

}

我的问题是如何让我的渲染方法使用最新的道具,而不是componentDidMount()在点击时渲染的道具?

标签: javascriptreactjsreact-reduxreact-component

解决方案


您不需要手动更新它,只需确保getPeople操作更新peopleList您的 Redux 状态即可。如果是这样,那么 React 组件会在componentDidUpdate.


推荐阅读