javascript - 如何在 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()
在点击时渲染的道具?
解决方案
您不需要手动更新它,只需确保getPeople
操作更新peopleList
您的 Redux 状态即可。如果是这样,那么 React 组件会在componentDidUpdate
.
推荐阅读
- solr - Apache solr slave 在索引完成之前被复制
- cmake - CMake CXXFlags -O2 / -O3
- python-3.x - 使用 matplotlib 绘制日期时间数据时出错
- angular - 带有Angular的highcharts将http值获取到打字稿
- codeigniter - 不会在 __constrruct 函数上重定向 - Codeigniter 4
- sql - 如何根据事件在 SQL 中计算客户保留率?
- nginx - CI/CD 如何为 HTTPS Web 服务器工作?
- image - 用 Yolo v4 算法检测大灰度图像中的小物体
- azure - Azure 数据工厂 - 将文件复制到基于 json 配置文件的文件夹列表
- tensorflow - 如何在 Keras 的多类分类中计算一个类的 AUC?