在渲染一个从后端获取的列表时出现错误:indicating it's undefined,我去查看了控制台日志,确认数组中有 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>
)
}
}
控制台日志:
after setting state
index.js:21 (3) ["one", "two", "three"]
index.js:32 after API responded
index.js:33 (5) [{…}, {…}, {…}, {…}, {…}]
请问,为什么 .state.pubsubtopics 是未定义呢?
原文由 Michael 发布,翻译遵循 CC BY-SA 4.0 许可协议
找到指定的行号,检查代码中使用的所有括号
例如改前是这样的:
这个是更正后:
我之前用这种方法操作的
你试试看看能不能解决