仅尝试呈现从我的后端获取的项目列表,但收到此错误指示它未定义。但是,当我查看控制台日志时,我可以看到该组件的状态在数组中肯定有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) [{…}, {…}, {…}, {…}, {…}]
有人知道为什么说this.state.pubsubtopics是未定义的吗?
答案 0 :(得分:3)
检查代码中指定行号的所有方括号,例如:
就我而言,这是引发错误-
const [query, setQuery] = useState['']
当我纠正此问题时,
const [query, setQuery] = useState('')
答案 1 :(得分:1)
您可以在数组的for..of
迭代中进行破坏,因为您要迭代的内容是不可破坏的。您实际上是在每次迭代中尝试这样做
const [index, value] = this.state.pubsubtopics[0]
// this is equivalent to const [index, value] = "one", for example.
您要使用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);
}
答案 2 :(得分:0)
添加此行代码和index.js的结尾
serviceWorker.unregister();
然后确保您导入了它,或者如果对其进行了注释,请取消注释导入代码,这样它将起作用。