在将react升级到16.3
版本之前,我会根据属性中的更改调用一个方法,如下所示:
componentWillReceiveProps(nextProps){
if(this.props.country.length !== nextProps.country){
doSomething(); //example calling redux action
}
}
在16.3
版本上,componentWillReceiveProps
是不安全的,我们必须使用getDerivedStateFromProps
。但是,这个方法返回一个对象,我不知道如何从它内部调用方法,就像调用componentWillReceiveProps
一样
发布于 2018-06-02 05:54:12
对于这种情况,使用componentDidUpdate
对OP来说很好,但我发现自己需要getDerivedStateFromProps
,所以我必须将我的自定义函数设为静态函数,并在getDerivedStateFromProps
中使用类的名称调用它。如下所示:
componentDidMount() {
const something = ClassComponentName.runThisFunction();
this.setState({ updatedSomething: something });
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.key !== prevState.key) {
return {
updatedSomething: ClassComponentName.runThisFunction()
};
}
return null;
}
static runThisFunction() {
//do stuff and return value
}
为了澄清,这是在加载时以及新道具到达时更新组件的状态。这无疑将我带回了我的类型化语言时代。希望它能帮上忙!
发布于 2019-10-09 21:21:28
如果你需要在"getDerivedStateFromProps“中调用一个函数,你可以把这个函数放在构造器的状态中,然后从状态中获取这个函数在"getDerivedStateFromProps”中。
在构造函数中将函数置于状态:
constructor(props){
super(props);
this.state = {
func1:this.func1.bind(this)
}
}
从getDerivedStateFromProps中的状态获取函数:
getDerivedStateFromProps(props,state){
return {
model:state.func1(props.model)
}
}
https://stackoverflow.com/questions/49664867
复制相似问题