对 ReactJS 中的props更改采取行动

IT技术 javascript reactjs
2021-04-26 00:42:43

我需要在我的 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 实践?还有其他“好”的方法可以做到吗?

3个回答

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

但是,当您根据以前的状态更新状态时,请使用功能性 setState 方法

检查此答案以获取更多详细信息

何时使用函数式 setState

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

根据最新的 RFC to React

从 props/state 派生的 state

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

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

从 v16.3.0 开始,您将使用

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

我想为从 Google 来到这里的任何其他人更新此答案。截至v16.8.6,componentWillReceiveProps已被标记为旧版,不建议使用。相反,您应该componentDidUpdate根据新props和以前的props/以前的状态使用和更新您的状态。

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

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

react更新生命周期

componentDidUpdate()

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

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

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