reactjs - 在 React 的 getDerivedStateFromProps 中调用异步函数
问题描述
当状态更新时,我需要更新表。因此,我尝试在 getDerivedStateFromProps 中调用函数更新,但似乎我无法在 getDerivedStateFromProps 中使用“this”。有没有办法做到这一点?预先感谢。
static getDerivedStateFromProps(props, state) {
if(props.newValue != state.newValue) {
this.updateTable();
return {
newValue : props.newValue
}
}
return null;
}
解决方案
updateTable
是一个sideEffect
不需要存在的函数getDerivedStateFromProps
getDerivedStateFromProps
有意编写为静态函数,因此您无法从中调用类实例函数
为了处理 sideEffect 你必须在 componentDidUpdate 函数中执行它们
componentDidUpdate(prevProps, prevState) {
if(this.props.newValue != prevProps.newValue) {
this.updateTable();
}
}
推荐阅读
- dom - 找出 DOM 树中节点的位置?
- scala - Store Comonad 和 Representable Store Comonad 在函数式编程中有什么区别?
- javascript - JS获取以逗号+最后一个单词分隔的单词长度
- laravel - 无法使用 Supervisor 启动 laravel-echo-server
- php - 从给定路径中删除文件和文件夹
- python - LSTM 在预测和基本事实之间具有系统偏移
- matrix - 在 Maxima 中,如何获得矩阵的行总和?
- java - 在 Primefaces 中导出 .pdf 后如何重定向到其他页面?
- symfony - 使用 FormBuilder 时如何修复“变量不存在”?
- typescript - 可选接口成员的打字稿强制实现