开发者问题收集

TypeError:undefined 不可迭代(无法读取属性 Symbol(Symbol.iterator))

2019-03-22
354115

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

3个回答

检查指定行号的代码中使用的所有括号。示例 -

就我而言,这是引发错误 -

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

当我更正此问题时,

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

这对我来说工作正常。
请检查这是否解决了您的问题。

Sumit Jadiya
2020-07-17

如果您最近更新了 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']]
]);
Joel Thomas Jawhar
2021-11-08

您无法在数组的 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);
}
Kevin Chavez
2019-03-22