无法读取未定义的属性图

时间:2019-07-04 14:48:18

标签: javascript reactjs

为了测试我对map()的理解,我从Starwars api中“获取”了数据  url:'https://swapi.co/api/people'并将其分配给const'data'

因为我只对映射结果[]中的字符感兴趣,所以我创建了一个指向该数组的const char,即。 const char = data.results。当我尝试映射数组时,出现错误“无法读取'map'的属性未定义。”在尝试对其执行映射功能之前,我进行了一些置信度检查(console.logs)以确认数组char存在。确实...所以我不确定为什么以下内容不起作用char.map((ele)=>             )

我还尝试了映射,并认为它与结果数组完全相同,并且映射工作正常。显然,我缺少一些东西。任何帮助将不胜感激

//根据选择从Web获取数据     const [data,isloading] = useFetch('https://swapi.co/api/people');

// test to see if we received from useFetch
console.log('Here is the loaded Data', data);

// Just want to map the characters in the Results array so point chars  to the results array in data
const chars = data.results;
console.log(`Check that chars and data.results are equal", ${data.results === chars}`)

// Now Show the Characters
console.log('Here are the Characters from Website after pointing to data.results', chars);
console.log('Here are the Characters using the static array', charsStatic)


const characterList = chars.map((ele) => 
        <Card key={ele.name} name={ele.name} height={ele.height} hair={ele.hair_color} skin={ele.skin_color} vehicle={ele.vehicles} />)

return (
    <div>
        <h1>List of Starwar Characters</h1>
        <div className='container'>
        {isloading ? "Waiting for Data" : characterList}
        </div>
    </div>
);

}

我希望能够映射chars数组,因为当我将chars登录到控制台时我可以清楚地看到它。相反,我收到了“无法读取未定义的属性映射”,但对我来说,char数组已定义;(

1 个答案:

答案 0 :(得分:1)

基于错误,我怀疑您被异步数据问题所困扰。 Console.log将在加载完成后显示数据,即使在调用代码行时尚未加载完成(在chrome上,您也会在工具提示中看到一些i,让您知道该值是经过计算的)。

并检查data.results ===字符是否以true表示,因为undefined === undefined为true。

尝试一下:

if (!isLoading) {
const characterList = chars.map((ele) => 
        <Card key={ele.name} name={ele.name} height={ele.height} hair={ele.hair_color} skin={ele.skin_color} vehicle={ele.vehicles} />)

return (
    <div>
        <h1>List of Starwar Characters</h1>
        <div className='container'>
        {isloading ? "Waiting for Data" : characterList}
        </div>
    </div>
);
}
else
{
    return (
        <div>
            <h1>List of Starwar Characters</h1>
            <div className='container'>
            Waiting for Data
            </div>
        </div>
}

这不是一个很好的解决方案,但是如果问题确实与异步有关,则应该可以使用。关键是直到isLoading为false时才调用.map。