首页 > 解决方案 > 变量未定义(TypeError:无法读取属性'todos' of null)ReactJS

问题描述

这是我下面的所有代码。当我运行它时,我收到此错误(TypeError: Cannot read property 'todos' of null )todos not found at this linevar todos=this.state.todos;

我的 App.js 文件

import React, { Component } from 'react';
class App extends Component {
    getInitialState (){
        return{
            todos:['washup',"hi","hello","up"]
        }
    }

render() {
      var todos=this.state.todos;

在此处添加代码

 todos=todos.map(function(item,index){
              return(
                <li>item</li>
              );
              }

      );

到这里

    return (
      <div id="App">
            <ul>{todos}</ul>
          )
   } )

      </div>
    );
  }
}


export default App;

这是我的 index.js 文件

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from `'./registerServiceWorker';`

ReactDOM.render(<div>
                     <App>Here is my Buttonas</App>
                </div>, document.getElementById('root'));
registerServiceWorker();

编辑 新错误

TypeError:无法读取未定义的属性“地图”

在这一行 todos=todos.map(function(item,index){

现在是什么错误?

标签: javascriptreactjs

解决方案


getInitialState()仅用于createReactClass(). 使用 ES6 类时,您只需将状态设置为属性:

请参阅在反应文档中设置初始状态:

在 ES6 类中,您可以通过分配来定义初始 this.state状态constructor

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

        this.state = {
            todos: ['washup',"hi","hello","up"],
        }
    }

    // ...
}

要不就

class App extends Component {
    state = {
        todos: ['washup',"hi","hello","up"],
    }

    // ...
}

使用createReactClass(),您必须提供一个单独的 getInitialState方法来返回初始状态:

var App = createReactClass({
    getInitialState: function() {
        return {
            todos: ['washup',"hi","hello","up"],
        };
    },

    // ...
});

推荐阅读