setstate不会设置状态

时间:2019-09-18 01:22:55

标签: reactjs asynchronous setstate

{petchStatus:[])的

设置状态并没有真正使fetchstatus数组为空。在for循环中进行调试时,fetchStatus在数组中仍具有其他值。

this.setState({fetchStatus: []}, () => {
   for (const proxy of proxies) {  
      fetch(authUrl, {
        method: 'POST',
        body: authBody  
      }).then((response) => {
          if (response.status !== 200){
            throw new Error(response.status);
          }
          return response;
        }).then((data) => {
          // expect fetchStatus to be empty array at the start of the first for loop
          fetchStatus.push("Fetched "+authUrl);
          // setting fetchStatus to ["Fetched"+authUrl}
          // when debugging at the first for loop, it's observed that fetchStatus is [otherArrItemsnotYetcleared, "Fetched"+authUrl)
          this.setState({fetchStatus});
       })

2 个答案:

答案 0 :(得分:1)

在示例中不清楚,但是假设fetchStatusthis.setState之前被分配了。

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = { fetchStatus: ["initial data"] };
  }

  componentDidMount() {
    let fetchStatus = this.state.fetchStatus;

    console.log(fetchStatus); // ["initial data"]

    this.setState({ fetchStatus: [] }, () => {
      // fetchStatus is still referencing the initial array data.
      // The value in state has been updated so you need
      // to reassign to the new array value.
      console.log(fetchStatus); // ["initial data"]

      fetchStatus = this.state.fetchStatus;

      console.log(fetchStatus); // []

      this.setState({ fetchStatus: ["later data"] });
    });
  }

  render() {
    return null;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

答案 1 :(得分:0)

setState()是异步的,因此您应该这样使用

//fetchStatus.push("Fetched "+authUrl);
//this.setState({fetchStatus});

this.setState({fetchStatus: this.state.fetchStatus.concat("Fetched "+authUrl)});