在React JS中getDerivedStateFromProps中的多个属性验证

5

我正在尝试将我的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 accordingly

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
  

我的问题是,在 componentWillReceiveProps 中我如何在 getDerivedStateFromProps 中进行多个 props 验证。有人能给我解释一下吗?

我尝试了以下代码,但它不会进入下一个 if 语句块!

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,
  };
}

期望输出两个控制台日志,但只看到第一个控制台的日志!


@skyboyer 你想展示一些例子吗? - Godfrey
1个回答

16

只需使用中间变量来堆叠更改。

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;
}

正如 @V-SHY 所建议的,确保我们至少有一个需要提供的属性是有意义的。否则,最好返回 null 以避免不必要的重新渲染。

return Object.keys(update).length ? update : null;

我在返回更新之前检查对象键的长度,这样我将返回null而不是空对象作为结果。 - V-SHY

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接