简体   繁体   中英

Setting state from external variable - React.js

Why is it that I can set the state of a class with an external variable?

So in my html file, ive already got a array which I am calling to via react class. Namely window.fbApiResponse

Then I try to run the following -

var App = React.createClass({

  getInitialState: function() {

    return {
        fb_api_nodes: []
    }

  },

  componentDidMount: function() {
       // console.info(this.state.jobs);
      console.info(window.fbApiResponse); // Returns array to console
            const fb_api_nodes = window.fbApiResponse;
            this.setState({ fb_api_nodes });

            console.log("state");
            console.log(this.state); // Returns empty array to console.

  },

The state doesn't get set, and returns an empty response when logged to console.

It's a bad practice to setState in a componentDidMount method. You should instead use a dedicated method to set your state. Furthermore, why would you need to set the state after the first render? can't you pass it on as props?

Try to clone the array instead:

// code....
const fb_api_nodes = window.fbApiResponse.splice(0);
// code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM