【问题标题】:Take an action on props change in ReactJS对 ReactJS 中的 props 更改采取行动
【发布时间】:2018-02-28 09:54:19
【问题描述】:

我需要在我的 React 组件中使用当前的 props 和以前的 props 值。 所以我就这样做了

state = {
    current: null,
    previous: null,
};

componentWillReceiveProps(nextProps) {
    if (nextProps.amount !== this.state.current) {
        this.setState({previous: this.state.current, current: nextProps.amount});
    }
}

...

render() {
    const {previous, current} = this.state;

    return (
        ...
        <CountUp className="counter" start={previous} end={current} duration={1}/>
        ...
    )
}

它工作得很好,但是这样做是一种好的 React 实践吗?还有其他“好”的方法吗?

【问题讨论】:

  • setState(prevState) 由 React 提供,props 都是可选的。

标签: javascript reactjs


【解决方案1】:

截至v16.2.0componentWillReceiveProps 是根据道具更改更新状态的正确位置,并且由于您想在渲染中同时使用当前状态和先前状态,因此您需要维护两个不同的状态变量正在做

但是,当您根据之前的状态更新状态时,请使用函数式 setState 方法

查看此答案了解更多详情

When to use functional setState

componentWillReceiveProps(nextProps) {
    if (nextProps.amount !== this.state.current) {
        this.setState(prevState => ({ previous: prevState.current, current: nextProps.amount }));
    }
}

根据最新的 RFC 来 React

从 props/state 派生的状态

这种模式的目的是计算一些从 props 派生的值,以便在渲染期间使用。

通常componentWillReceiveProps 用于此目的,但如果计算速度足够快,则可以在render 中完成。:

从 v16.3.0 开始,您将使用

static getDerivedStateFromProps(nextProps, prevState) {
    if (
      !prevState ||
      prevState.current !== nextProps.amount
    ) {
      return {
        previous: prevState.current,
        current: nextProps.amount
      };
    }
}

【讨论】:

  • 对于 2019 年阅读本文的任何人,请查看我的 updated answer。不建议使用componentWillReceiveProps
  • @afryingpan 你的回答不正确,最好使用getDerivedStateFromProps
【解决方案2】:

我想为来自 Google 的其他人更新此答案。从v16.8.6 开始,componentWillReceiveProps 已被标记为旧版,不建议使用。相反,您应该使用componentDidUpdate 并根据新道具和先前的道具/先前状态更新您的状态。

componentDidUpdate(prevProps, prevState) {
   if (this.props.someVal !== prevState.someVal) {
     this.setState({ previous: prevState.someVal, current: this.props.someVal });
   }
}

显然,您是否检查以前的状态或以前的道具取决于您的判断/情况。您可以使用或不使用参数来实现componentDidUpdate,但如果您想要prevState,您必须声明prevProps

React Update Lifecycle

componentDidUpdate()

【讨论】:

    【解决方案3】:

    您可以在 setState 对象中使用箭头函数。 像这样:

    this.setState((prevState) => {
          return { yourState: prevState.yourState }
        })

    prevState 是默认名称,但您可以根据需要替换名称

    【讨论】:

      猜你喜欢
      • 2013-09-10
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 2021-12-19
      • 2021-09-05
      • 2023-03-03
      相关资源
      最近更新 更多