gpt4 book ai didi

javascript - this.state.data.map 不是一个函数,即使我有一个数组,也会继续显示

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

我正在接收一个对象并推送到一个数组。我可以在 console.log 中看到该数组,但它仍然拒绝映射 li。

我做错了什么?

state = {
startDate: null,
endDate: null,
data: []
}

componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data =>
this.setState({ data: this.state.data.push(data) }),
console.log(this.state.data)
)
}

render() {
return (
<div>
<ul>
{this.state.data.map(item => (
<li key={item.id}>{item.id} - {item.title}</li>
)}
</ul>
</div>
)
}

控制台.log:

[]
0: {userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"}
length: 1

最佳答案

Array.push的返回值是

The new length property of the object upon which the method was called.

所以,你基本上覆盖了 data在你的状态中通过数组的长度而不是数组本身,

使用 data => this.setState(prevState => ({ data: [...prevState.data, data] }))
更新您的状态

class App extends React.Component {
state = {
startDate: null,
endDate: null,
data: []
};

componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(
data => this.setState(prevState => ({ data: [...prevState.data, data] }))
);
}

render() {
return (
<div>
<ul>
{this.state.data.map(item => {
return (
<li key={item.id}>
{item.id} - {item.title}
</li>
);
})}
</ul>
</div>
);
}
}

ReactDOM.render(<App />, document.querySelector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

关于javascript - this.state.data.map 不是一个函数,即使我有一个数组,也会继续显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58938437/

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