【问题标题】:Problem with replacing componentWillReceiveProps with static getDerivedStateFromProps用静态 getDerivedStateFromProps 替换 componentWillReceiveProps 的问题
【发布时间】:2020-06-08 02:46:14
【问题描述】:

我有Dropdown comp,用户可以在其中选择一些过滤器。

我也有按钮clear-filters,当用户单击该按钮时,父组件中的过滤器消失了,但在dropdown comp 中仍然保持选中的过滤器。

这意味着我的下拉列表没有像以前那样正确更新UNSAFE_componentWillReceiveProps

带有UNSAFE_componentWillReceiveProps()的下拉组件:

  state = {
     options: props.options || []
  };

  componentDidMount() {
    this.setSelectedOptions(this.props);
    document.addEventListener('mousedown', (e) => this.handleClickOutside(e));
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  UNSAFE_componentWillReceiveProps(props) {
    this.setSelectedOptions(props);
  }

这是 Dropdown 迁移版本,它不像以前那样工作:

  state = {
      options: props.options || []
  };

  componentDidMount() {
    this.setSelectedOptions(this.props);
    document.addEventListener('mousedown', (e) => this.handleClickOutside(e));
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { options } = nextProps;

// CHECKING DOES SOME OPTIONS PROPERTIES ARE CHANGED OR NOT
    options.forEach((filter, i) => {
      if (filter.selected !== prevState.options[i].selected) {
        return { options };
      }
    });
    return null;
  }

有什么建议吗?

【问题讨论】:

    标签: javascript reactjs typescript next.js


    【解决方案1】:

    从快速检查看来,这里唯一的问题是您从错误的地方返回“选项”。请注意,当您在数组上使用 forEach 时,您传递的是一个函数,该函数与数组的每个元素一起执行。当您返回 { options } 时,您只是从传递给 forEach 的函数返回,而不是实际从 getDerivedStateFromProps 返回。

    我建议改为在 getDerivedStateFromProps 范围内创建一个标志变量 (shouldReturnOptions):

    static getDerivedStateFromProps(nextProps, prevState) {
      const { options } = nextProps;
      let shouldReturnOptions = false;
    
      options.forEach((filter, i) => {
        if ((!shouldReturnOptions) && (filter.selected !== prevState.options[i].selected)) {
          shouldReturnOptions = true;
        }
      });
    
      if (shouldReturnOptions) {
        return { options };
      }
      return null;
    }
    

    【讨论】:

    • 感谢您的回答和时间。问题仍然存在,但这个答案很有帮助!
    • @MichelJames 太好了,当你设法解决剩下的问题时告诉我,我很想知道出了什么问题!
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    相关资源
    最近更新 更多