渲染列表时出现错误 TypeError: undefined is not iterable 如何解决?

在渲染一个从后端获取的列表时出现错误: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 许可协议
阅读 3.1k
1 个回答

找到指定的行号,检查代码中使用的所有括号

例如改前是这样的:

 const [query, setQuery] = useState['']

这个是更正后:

 const [query, setQuery] = useState('')

我之前用这种方法操作的
你试试看看能不能解决

原文由 Sumit Jadiya 发布,翻译遵循 CC BY-SA 4.0 许可协议
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题