简体   繁体   English

通过外部变量设置状态-React.js

[英]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. 因此,在我的html文件中,我已经通过react类调用了一个数组。 Namely window.fbApiResponse 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. 在componentDidMount方法中设置setState是一种不好的做法。 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...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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