只是试图呈现从我的后端获得的项目列表,但收到此错误表明它未定义。但是,当我检查控制台日志时,我可以看到该组件的状态在数组中肯定有 5 个项目。
class PubSubTopics extends React.Component{
constructor(props){
super(props);
this.state = {
pubsubtopics: ['one', 'two', 'three'],
}
}
componentDidMount() {
this.callBackEndAPI()
.then(res =>
this.setState({pubsubtopics: res.express}))
.catch(err => console.log(err));
console.log('after setting state');
console.log(this.state.pubsubtopics);
}
callBackEndAPI = async () => {
const response = await fetch('/listtopics');
const body = await response.json();
if(response.status !== 200){
throw Error(body.message)
}
console.log('after API responded');
console.log(body.topics);
return body.topics;
}
render(){
const list = [];
for(const[index, value] of this.state.pubsubtopics){
list.push(<li key={index}>{value}</li>)
}
return(
<div>
<ul>
{list}
</ul>
<button onDoubleClick={this.handleClick}/>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
控制台日志:
after setting state
index.js:21 (3) ["one", "two", "three"]
index.js:32 after API responded
index.js:33 (5) [{…}, {…}, {…}, {…}, {…}]
Run Code Online (Sandbox Code Playgroud)
知道为什么说 this.state.pubsubtopics 是未定义的吗?
小智 11
如果您最近更新了 MacOS,并且突然出现此错误,则一定是因为 MacOS Monterey 未在操作系统列表中列出。
将此行添加到index.js的顶部,然后此错误将被修复。
const nameMap = new Map([
[21, ['Monterey','12']],
[20, ['Big Sur', '11']],
[19, ['Catalina', '10.15']],
[18, ['Mojave', '10.14']],
[17, ['High Sierra', '10.13']],
[16, ['Sierra', '10.12']],
[15, ['El Capitan', '10.11']],
[14, ['Yosemite', '10.10']],
[13, ['Mavericks', '10.9']],
[12, ['Mountain Lion', '10.8']],
[11, ['Lion', '10.7']],
[10, ['Snow Leopard', '10.6']],
[9, ['Leopard', '10.5']],
[8, ['Tiger', '10.4']],
[7, ['Panther', '10.3']],
[6, ['Jaguar', '10.2']],
[5, ['Puma', '10.1']]
]);
Run Code Online (Sandbox Code Playgroud)
您无法在for..of数组的迭代中进行破坏,因为您尝试迭代的内容是不可破坏的。你本质上是在每次迭代中尝试这样做
const [index, value] = this.state.pubsubtopics[0]
// this is equivalent to const [index, value] = "one", for example.
Run Code Online (Sandbox Code Playgroud)
您想要做的是 use this.state.pubsubtopics.entries(),它返回一个键值对数组。这是一个例子:
const arr = ['a', 'b'];
// arr.entries() is [[0, 'a'], [1, 'b']]
for (const [index, element] of arr.entries()) {
// const [index, element] = [0, 'a'] on 1st iteration, then [1, 'b'], etc.
console.log(index, element);
}
Run Code Online (Sandbox Code Playgroud)
检查指定行号处代码中使用的所有括号。例如:
在我的情况下,这是抛出错误 -
const [query, setQuery] = useState['']
Run Code Online (Sandbox Code Playgroud)
当我纠正这个时,
const [query, setQuery] = useState('')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
93731 次 |
| 最近记录: |