javascript - 变量未定义(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){
现在是什么错误?
解决方案
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"],
};
},
// ...
});
推荐阅读
- javascript - JavaScript:当数组为空时解构对象数组时出错
- extjs - ExtJs:为什么 numberfield 在显示数据时会自动将 null 转换为 0
- php - 为什么 PHP 会在输入时删除文件的内容?
- sql - 将字符串转换为时间戳并在 BigQuery SQL 中使用 timestamp_diff
- ansible - 如何在 ansible 查找模块中使用模式、年龄、年龄标记选项
- ios - iOS 12.4.1 发布在苹果商店拒绝 ipad 设备时崩溃
- visual-studio-2012 - VSCode 中的权限被拒绝(公钥)
- css - Angular Material datepicker上的占位符左边距/填充?
- android - 无法使用 Xamarin.UITest 截屏
- c++ - C++ 如何防止 Winapi::FreeLibrary 删除变量?