我正在尝试将我的React版本从react 15升级到16,因此在这样做的同时面临getDerivedStateFromProps中的一个挑战。在ComponentWillReceiveProps中,
componentWillReceiveProps(nextProps) {
if (nextProps.postDetails !== []) {
this.setState({
postDetails: nextProps.postDetails
});
}
if (nextProps.userData.length === 2) {
this.setState({
userData: nextProps.userData
});
}
}
// in the above am checking two different props and setting the value accordinglyRun Code Online (Sandbox Code Playgroud)
在getDerivedStateFromProps中,
static getDerivedStateFromProps(props, prevState) {
if (prevState.value !== props.value) {
return {
value: props.value
}
}
}
//here the problem is ,am unable to do multiple props validations here
Run Code Online (Sandbox Code Playgroud)
我的问题是,就像我在componentWillReceiveProps中所做的那样,如何在propderivedstatefromprops中进行多个props验证。有人可以澄清一下吗。
我在下面这样尝试过,但是如果没有,它就不会出现!
let xx = true;
let yy = true;
if (xx) {
console.log("if 1");
return {
value: nextProps.someValues,
};
}
if (yy) {
console.log("if 2");
return {
value2: nextProps.someValues2,
};
}Run Code Online (Sandbox Code Playgroud)
预期o / p两个控制台日志,但如果仅控制台,则将获得第一!
只是使用中间变量来堆叠更改
getDerivedStateFromProps(props, state) {
let update = {};
if (props.postDetails !== []) {
update.postDetails = props.postDetails;
}
if (props.userData && props.userData.length === 2) {
update.userData = props.userData;
}
return update;
}
Run Code Online (Sandbox Code Playgroud)
正如建议@ V-SHY,确保我们至少需要提供我一个属性是有道理的。否则,我们最好返回null以避免不必要的重新渲染。
return Object.keys(update).length ? update : null;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
895 次 |
| 最近记录: |