【问题标题】:setState not updating state [duplicate]setState 不更新状态 [重复]
【发布时间】:2018-04-08 16:25:37
【问题描述】:

我正在从一个文件中导出 const 并将其导入到另一个文件中,如下所示:

constants.js

export const radio = {
  id: 0,
  name: 'station name',
  encodedName: 'stationName',
  url: 'http://www.some-station.io/',
  src: 'http://127.0.0.1:80/autodj',
};

App.js

import React, { Component } from 'react';
import RadioService from './services/radio';
import { radio } from './constants';

class App extends Component {
  constructor() {
    super();
    this.state = {
      stream: {
        np: undefined,
        src: undefined,
        playing: false
      }
    };
  }

  componentWillMount() {
    this.startStream();
  }

  startStream = () => this.setState({ stream: { np: radio.name, src: radio.src } });

  render() {
    return (
      <div>
        <h4>Hello World...</h4>
      </div>
    );
  }
}

export default App;

我希望我的初始状态与构造函数中设置的一样,然后在 componentWillMount 上,我想使用常量文件中的值设置状态,然后围绕组件和流添加更多逻辑。

但是我发现,我的状态没有被更新,如果我在调用 setState 后控制台日志,状态仍然是未定义的,如果我引入了一个需要状态值的方法,稍后在执行堆栈中,它是未设置。

示例:

  startStream = () => {
    this.setState({ stream: { np: radio.name, src: radio.src } });
    this.exampleMethod();
  };

  exampleMethod = () => console.log(this.state);

这会返回:

{stream: {…}}stream: {np: undefined, src: undefined, playing: false}

但是我可以在构造函数中设置一些值,但是尝试设置进一步的状态并没有应用

示例 2:

class App extends Component {
  constructor() {
    super();
    this.state = {
      stream: {
        np: radio.name,
        src: radio.src,
        playing: false
      }
    };
  }

  componentWillMount() {
    this.startStream();
  }

  startStream = () => {
    this.setState({ ...this.state, stream: { playing: true } });
    this.exampleMethod();
  };

【问题讨论】:

  • 我相信setState 函数是异步的。因此,您无法在调用该函数后立即获得新状态。尝试将控制台日志移动到渲染方法。
  • 尝试在构造函数中添加this.startStream = this.startStream.bind(this);
  • 这真的不会给您带来错误吗?因为它应该:“this”不在函数 startStream 的上下文中。您需要使用 this.startStream = this.startStream.bind(this); 在构造函数中绑定它另一件事:您应该将构造函数中的道具传递给超类,因此将其更改为 constructor(props) { super(props); ... }。这将解决道具未更新的进一步问题。

标签: reactjs


【解决方案1】:

setState 是一个异步函数。你不能期望状态在 setState 语句之后立即更新。

但是,您可以通过以下任一方式检查状态:

  1. 在你的 render() 方法中添加一个console.log(this.state)

  2. 或者在setState之后使用回调

    this.setState({ ...this.state, 流: { 播放: true } }, () => { 控制台.log(this.state); // 应该显示更新的状态 });

【讨论】:

    【解决方案2】:

    setState 是异步的,所以如果你在 console.log 之后立即获取新的状态,你将不会得到。

    setState in reactjs is Async or Sync

    【讨论】:

      猜你喜欢
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      • 2018-02-27
      • 1970-01-01
      • 2019-05-31
      • 2021-01-28
      相关资源
      最近更新 更多