Javascript ReactJS this.state null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26408388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:52:19  来源:igfitidea点击:

ReactJS this.state null

javascriptstatereactjs

提问by Matthew Wisniewski

Let me preface this by saying I am a novice to ReactJS. I am trying to learn by making a simple site that populates data using React. I have a JSON file that contains link data that will be looped through with map.

让我先说我是 ReactJS 的新手。我正在尝试通过创建一个使用 React 填充数据的简单站点来学习。我有一个 JSON 文件,其中包含将通过地图循环的链接数据。

I have tried setting it as the components state then passing it to the navbar links via a prop but I am getting "Uncaught TypeError: Cannot read property 'data' of null"

我尝试将其设置为组件状态,然后通过道具将其传递给导航栏链接,但我收到“未捕获的类型错误:无法读取 null 的属性‘数据’”

I tried to look around for solutions but could not find anything.

我试图四处寻找解决方案,但找不到任何东西。

Note: When I try to hard code an object and map through it that way it returns map is undefined. However I am not sure that is directly related to the setState error.

注意:当我尝试硬编码一个对象并通过这种方式映射它时,它返回 map 是未定义的。但是我不确定这是否与 setState 错误直接相关。

/** @jsx React.DOM */

var conf = {
    companyName: "Slant Hosting"
  };

var NavbarLinks = React.createClass({
  render: function(){
    var navLinks = this.props.data.map(function(link){
      return(
        <li><a href={link.target}>{link.text}</a></li>
      );
    });
    return(
      <ul className="nav navbar-nav">
        {navLinks}
      </ul>
    )
  }
});

var NavbarBrand = React.createClass({
  render: function(){
    return(
      <a className="navbar-brand" href="#">{conf.companyName}</a>
    );
  }
});

var Navbar = React.createClass({
  getInitalState: function(){
    return{
      data : []
    };
  },
  loadNavbarJSON: function() {
    $.ajax({
      url: "app/js/configs/navbar.json",
      dataType: 'json',
      success: function(data) {
        this.setState({
          data: data
        });
        console.log(data);
        console.log(this.state.data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  componentDidMount: function(){
    this.loadNavbarJSON();
  },
  render: function(){
    return(
      <nav className="navbar navbar-default navbar-fixed-top" role="navigation">
        <div className="container-fluid">
          <div className="navbar-header">
            <NavbarBrand />
          </div>
          <NavbarLinks data={this.state.data} />
        </div>
      </nav>
    );
  }
});

var Header = React.createClass({
  render: function(){
    return(
      <Navbar />
    );
  }
});

React.renderComponent(
  <Header />,
  document.getElementById('render')
);

回答by yussan

Using ES6, the initial state must be created in your constructor for the React component class, like this:

使用 ES6,必须在 React 组件类的构造函数中创建初始状态,如下所示:

constructor(props) {
    super(props)
    this.state ={
    // Set your state here
    }
}

See this documentation.

请参阅此文档

回答by Filip Savic

This question has already been answered, but I came here by having a problem that can easily happen to anyone.

这个问题已经得到了回答,但我来到这里是因为遇到了一个任何人都容易发生的问题。

I was getting a console.log(this.state)to log nullin one of my methods, just because I didn't write:

我正在console.log(this.state)登录null我的一种方法,只是因为我没有写:

this.handleSelect = this.handleSelect.bind(this);

this.handleSelect = this.handleSelect.bind(this);

in my constructor.

在我的构造函数中。

So, if you're getting a nullfor this.state in one of your methods, check if you have bounded it to your component.

因此,如果您null在其中一种方法中获得了this.state,请检查您是否已将其绑定到您的组件。

Cheers!

干杯!

Edit(because of @tutiplain's question)

编辑(因为@tutiplain 的问题)

Why was I getting nullfor this.state?

为什么我得到nullthis.state

Because I wrote console.log(this.state)in the method which wasn't bounded to my class (my handleSelect method). That caused thisto point to some object higher in the object hierarchy (most probably the windowobject) which doesn't have a property named state. So, by binding my handleSelectmethod to this, I assured that whenever I write thisin that method, it will point to the object in which the method is in.

因为我写console.log(this.state)的方法没有绑定到我的类(我的 handleSelect 方法)。这导致this指向对象层次结构中更高的某个对象(很可能是window对象),该对象没有名为state. 因此,通过将我的handleSelect方法绑定到this,我保证每当我this在该方法中写入时,它都会指向该方法所在的对象。

I encourage you to read a really good explanation for this here.

我建议你阅读这一个很好的解释在这里

回答by Blair Anderson

this.state.datais null in your example because setState()is async. Instead you can pass a callback to setState like so:

this.state.data在您的示例中为 null 因为setState()是异步的。相反,您可以像这样将回调传递给 setState:

loadNavbarJSON: function() {
    $.ajax({
      url: "app/js/configs/navbar.json",
      dataType: 'json',
      success: function(data) {
        console.log(data);

        this.setState({data: data}, function(){
          console.log(this.state.data);
        }.bind(this));

      }.bind(this),
    });
  }

https://facebook.github.io/react/docs/component-api.html#setstate

https://facebook.github.io/react/docs/component-api.html#setstate

回答by fl-web

More actual answer, for using ES7+ Classes:

更实际的答案,使用 ES7+ 类:

export class Counter extends React.Component {
  state = { data : [] };
  ...
}

ES6 Classes (alredy was answered)

ES6 类(已经回答)

export class Component extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data : [] };
  }
  ...
}

回答by Grigory Bogush

I had similar issue. In my case it was webpack-dev-servernot re-compiling my stuff on the run properly.
I just restarted the dev server to get it working again.

我有类似的问题。在我的情况下,它webpack-dev-server没有在运行时正确地重新编译我的东西。
我刚刚重新启动了开发服务器以使其再次工作。