这是给我一个错误的代码:
import React, { Component } from 'react'
import Header from './components/Header';
import Todo from './components/Todo';
class App extends Component {
state: {
list: [
{
title: "Take out trash",
completed: false,
id: 1
},
{
title: "Take dog for walk",
completed: false,
id: 2
},
{
title: "Doctor appointment",
completed: false,
id: 3
}
];
}
render() {
return (
<div className="container">
<Header number={this.state.list.length} />
<Todo/>
</div>
)
}
}
export default App
该消息说,当我将数组作为标头的属性传递时,它无法读取“ this”。我不是可以这样做吗?为什么关键字“ this”在类组件中未定义?
答案 0 :(得分:2)
是state = { }
而不是state: { }
。
答案 1 :(得分:2)
您设置的初始状态不正确。
应该是:
class App extends Component {
state = {
list: [
{
title: "Take out trash",
completed: false,
id: 1
},
{
title: "Take dog for walk",
completed: false,
id: 2
},
{
title: "Doctor appointment",
completed: false,
id: 3
}
];
}
或者,您可以在构造函数方法中进行设置,但这将实现相同的目的
答案 2 :(得分:1)
在您的帖子标题中,您提到“列表”引发了错误,而不是“ this”。根据您的意思,根本的问题会有所不同。我怀疑this.state
是未定义的,因此this.state.list
会引发错误,因此我的答案基于该假设,直到明确为止。
我通常在constructor
中声明初始状态,例如
import React, { Component } from 'react'
import Header from './components/Header';
import Todo from './components/Todo';
class App extends Component {
constructor(props) {
this.state = {
list: [
{
title: "Take out trash",
completed: false,
id: 1
},
{
title: "Take dog for walk",
completed: false,
id: 2
},
{
title: "Doctor appointment",
completed: false,
id: 3
}
]
}
}
render() {
return (
<div className="container">
<Header number={this.state.list.length} />
<Todo/>
</div>
)
}
}
export default App
我已经在自己的React Native应用程序中使用了您的状态声明,并得到了相同的错误。像我上面所做的那样初始化状态应该解决它。