gpt4 book ai didi

javascript - 谁能解释为什么我收到 map 功能错误

转载 作者:行者123 更新时间:2023-12-04 12:14:38 25 4
gpt4 key购买 nike

我正在尝试了解 api 获取,并且我遵循了这里的其他一些答案,但我一直在这个脚本上遇到一个奇怪的错误:

const fetcher = async () => {
const url = 'https://banana1.free.beeceptor.com/cars'
const response = await fetch(url) //once we fetch we get a resposne
const json_data = await response.json()
return json_data
}

const Publish = () => {
const [loading, setLoading] = useState(true)
const [choices, setChoices] = useState([])

useEffect(()=>{
const choiceGetter = async () => {
await fetcher().then(json_data=>{
setChoices(json_data);
setLoading(false);
console.log(json_data)
})
};
choiceGetter();
},[])

return(
<>
<h1>
{loading&&<>loading...</>}
{!loading&&choices&&
choices.map( (choice) => {
const {option,make} = choice;
return( <div key={car1}>
<h1>{option}</h1>
<h3>{make}</h3>
</div>)
} )
}
</h1>
</>
)
}
export default ApiTest

错误:

Unhandled Runtime Error
TypeError: choices.map is not a function

Source
.next/static/chunks/pages/index.js (56:24) @ ApiTest

54 | {loading&&<>loading...</>}
55 | {!loading&&choices&&
> 56 | choices.map( (choice) => {
| ^
57 | const {option,make} = choice;
58 | return( <div key={car1}>
59 | <h1>{option}</h1>

我什至尝试模仿以下内容:

ReactJs useState .map() is not a function

但它不工作......

最佳答案

问题

响应不是数组,而是对象。

// 20211006212847
// https://banana1.free.beeceptor.com/cars

{
"car1": {
"option": "lease",
"make": "toyota",
"body": "round",
"model": "camery",
"trim": "sle",
"year": 2020,
"color": "metalic gray"
},
"car2": {
"option": "finance",
"make": "nissan",
"body": "square",
"model": "sentra",
"trim": "xle",
"year": 2021,
"color": "army green"
}
}

所以 choices 状态不是数组。您正在改变状态不变量。

解决方案

渲染时将其转换为数组:

Object.values(choices).map(choice => ....

或者在state存储的时候进行转换:

useEffect(()=>{
fetcher().then(json_data => {
setChoices(Object.values(json_data));
setLoading(false);
});
},[]);

更新

如果您想使用对象的键(即“car”、“car2”等),则使用 Object.entries 返回键值对数组。

Object.entries(choices).map(([key, choice]) => {
const {option, make} = choice;
return (
<div key={key}>
<h1>{option}</h1>
<h3>{make}</h3>
</div>
)
})

关于javascript - 谁能解释为什么我收到 map 功能错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69475458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com