gpt4 book ai didi

javascript - 当 items 是数组时,React items.map 不是函数?

转载 作者:行者123 更新时间:2023-11-30 13:55:16 24 4
gpt4 key购买 nike

加载 API 并且我得到的 .map 不是一个函数。一直在查看每个示例并完全按照它们进行操作,但仍然出现此错误。错误当然发生在 ul 标签中的 .map

class Login extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
};
}

componentDidMount() {
fetch(
"https://opentdb.com/api.php?amount=10&category=18&difficulty=easy&type=boolean"
)
.then(res => res.json())
.then(json => {
this.setState({ isLoaded: true, items: json });
});
}

render() {
var { isLoaded, items } = this.state;

if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="App">
<ul>
{items.map(item => (
<li key={item.results.question}>{item.results.question}</li>
))}
</ul>
</div>
);
}
}
}

export default Login;

最佳答案

您的实际数据来自 json.results,因此您需要将 json.results 设置为如下状态,

this.setState({ isLoaded: true, items: json.results });

你需要像这样迭代数组,

{ items.map(item => (
<li key={item.question}>{item.question}</li>
))}

Demo

关于javascript - 当 items 是数组时,React items.map 不是函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57423394/

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