【问题标题】:Accessing new state in current handler [duplicate]在当前处理程序中访问新状态 [重复]
【发布时间】:2019-03-13 10:49:38
【问题描述】:

我有一个处理程序可以更改我的 react 应用程序的某些状态,假设它会打乱状态条目data

state = {
   data:[1,2,3,4,5]
  };

 public handleShuffle = () => {
    const current = this.state.data;
    const shuffled = current
      .map((a: any) => [Math.random(), a])
      .sort((a: any, b: any): any => a[0] - b[0])
      .map((a: any) => a[1]);
    this.setState({
      ...this.state,
      data: shuffled
    });
    consoleLog(this.state.data[0])
  };

有没有办法在这个处理程序中访问这个新的洗牌数组,所以有一个不是 1 的日志,它是以前的状态,而是一个新的洗牌的?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    setState 在您将对象作为第一个传递时接受第二个回调参数:

    this.setState({ data: shuffled }, () => {
      this.state.data === shuffled // true
    }
    

    假设您在同一范围内,您实际上并不需要回调,因为您已经拥有 shuffled 中即将成为状态的值,您可以继续使用它。

    通常,如果您想等到this.state 更新并且组件已重新渲染,建议您使用componentDidUpdate 而不是setState 回调。

    请注意,setState 已经对您传入的对象进行了浅层比较,并合并到新的更新中。你不需要这样做:setState({ ...this.state }),这样做实际上是有害的。

    【讨论】:

      【解决方案2】:

      您可以将第二个参数传递给setState。 请试试这个:

      this.setState({
        ...this.state,
        data: shuffled
      }, () => console.log(this.state.data[0]));
      

      【讨论】:

        【解决方案3】:

        状态更新是异步的,setState 有回调

        试试这个

        public handleShuffle = () => {
        const current = this.state.data;
        const that = this;
        const shuffled = current
          .map((a: any) => [Math.random(), a])
          .sort((a: any, b: any): any => a[0] - b[0])
          .map((a: any) => a[1]);
        this.setState({
          ...this.state,
          data: shuffled
        }, ()=>{
           consoleLog(that.state.data[0])
        });
        };
        

        【讨论】:

          猜你喜欢
          • 2015-09-25
          • 2020-08-07
          • 2020-06-16
          • 1970-01-01
          • 2019-12-11
          • 2018-11-16
          • 2015-04-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多