我正在接收一个对象并将其推送到数组。我可以在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>
)
}
Console.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
答案 0 :(得分:4)
Array.push的返回值为
调用该方法的对象的新 length 属性。
因此,您基本上是在状态中用数组的长度而不是数组本身覆盖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>