reactjs - react js中通过getDerivedStateFromProps调用状态变化后的方法
问题描述
我有一个反应组件,我需要在 getDerivedStateFromProps 中的状态更改后调用一个方法。假设我有一个方法foo在 getDerivedStateFromProps 中的状态更改后被调用。
//state
state: {
"a": "",
"b": ""
}
static getDerivedStateFromProps(nextProps, currentState){
if(nextProps.show){
// nextProps.foo() function to be called after the state changes to "a": "Apple","b": "Ball"
return {
"a": "Apple",
"b": "Ball"
}
}
}
//The function in parent component
foo = () => {
console.log("Function called")
}
解决方案
调用props.foo()
取决于,props.show,
因此您可以使用componentDidUpdate
生命周期方法。
componentDidUpdate(prevProps) {
if (this.props.show !== prevProps.show && this.props.show) {
this.props.foo();
}
}
这意味着props.foo
将在 props.show 更改并且 props.show 为 true 时调用
推荐阅读
- angularjs - 从Angularjs中的数组中获取特定元素
- c# - 外键关系没有出现在 edmx 与 mysql 数据库与 asp mvc 与数据库第一
- angularjs - 在ajax formdata中获取415(不支持的媒体类型)发布到spring
- flutter - 如何在颤动中从 SelectableText 小部件中获取选定的文本
- json - 使用 Spark 2.4 识别空 JSON 文件
- c# - 在 Unity 中捕获 360 度屏幕截图会忽略 UI 层
- sql - 如何将一个 SQL 列转换为同一行的多个列?
- java - 在 Android 中,我如何实现一个全局触摸跟踪服务,即使屏幕上正在运行其他应用程序也能正常工作
- java - Spring Boot 配置问题中的 JWT 令牌
- oracle - 在 SQL Developer 中使用 DESCRIBE 获取其数据类型的列列表时如何按列名排序?