MBe*_*mam 13 reactjs react-native
在升级之前16.3
根据道具的变化对调用动作的版本作出反应我使用类似这样的代码:
componentWillReceiveProps(nextProps){
if(this.props.country.length !== nextProps.country){
doSomething(); //example calling redux action
}
}
Run Code Online (Sandbox Code Playgroud)
但在版本componentWillReceiveProps
的反应16.3
是不安全的,我们必须使用,getDerivedStateFromProps
但它说这个方法必须返回对象,我不知道我怎么可以模拟我以前componentWillReceiveProps
做的事情与做16.3
Dan*_*ane 18
是的,您需要返回一个对象,该对象是派生自的新状态nextProp
.根据文件:
getDerivedStateFromProps
应该返回一个更新状态的对象,或者返回null以指示新的props不需要任何状态更新.
但是既然你没有以任何方式更新你的状态componentWillReceiveProps
,你应该使用componentDidUpdate
而不是getDerivedStateFromProps
:
componentDidUpdate(prevProps){
if ( prevProps.country !== this.props.country.length ) {
doSomething(); //example calling redux action
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,使用OP很好,componentDidUpdate
但是我发现自己很需要,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
}
Run Code Online (Sandbox Code Playgroud)
为了澄清,这是在加载时以及新道具到达时更新组件的状态。这无疑使我回到了键入语言的时代。希望能帮助到你!
小智 7
如果你需要在“getDerivedStateFromProps”中调用一个函数,你可以把这个函数放在constructor中的state,然后从state中的“getDerivedStateFromProps”中获取这个函数。
在构造函数中将函数置于状态:
constructor(props){
super(props);
this.state = {
func1:this.func1.bind(this)
}
}
Run Code Online (Sandbox Code Playgroud)
从 getDerivedStateFromProps 中的状态获取函数:
getDerivedStateFromProps(props,state){
return {
model:state.func1(props.model)
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12526 次 |
最近记录: |