【问题标题】:TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
【发布时间】:2019-08-13 23:32:56
【问题描述】:

只是试图呈现从我的后端获得的项目列表,但收到此错误,表明它未定义。但是,当我检查控制台日志时,我可以看到组件的状态在数组中肯定有 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 是未定义的吗?

【问题讨论】:

  • “设置状态后”在 callBackEndAPI 函数完成并设置状态之前记录。您可以复制/粘贴您收到的整个错误消息吗?
  • TypeError: 无法读取未定义 PubSubTopics.render src/index.js:38 35 的属性“切片” 36 |渲染(){ 37 |常量列表 = []; > 38 | const pubsubtopics = this.state.pubsubtopics.slice(); | ^ 39 | for(const[index, value] of pubsubtopics.entries()){ 40 | list.push(
  • {value}
  • ) 41 | }
  • 在意识到后端的数组嵌套在一个键中后能够使其工作:this.setState({pubsubtopics: res.express.topics}))
  • 标签: reactjs


    【解决方案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);
    }
    

    【讨论】:

    • 我已将 .entries() 添加到 this.state.pubsubtopics 中,但它仍然抱怨“无法读取未定义的属性‘条目’”。似乎状态正在某个地方被清除。
    • 在意识到后端的数组嵌套在一个键中后能够使其工作:this.setState({pubsubtopics: res.express.topics}))
    【解决方案2】:

    检查代码中指定行号处使用的所有括号。例如:
    就我而言,这是抛出错误-

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

    当我纠正这个问题时,

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

    这对我来说很好。
    请检查这是否解决了您的问题。

    【讨论】:

      【解决方案3】:

      添加这行代码和index.js的结尾

      serviceWorker.unregister();
      

      然后确保你导入它,或者如果它被注释,取消注释导入代码,它会起作用。

      【讨论】:

      • 这样的答案并不能真正帮助任何人学习
      【解决方案4】:

      如果您最近更新了您的 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']]
      ]);
      

      【讨论】:

        猜你喜欢
        相关资源
        最近更新 更多
        热门标签