如何将对象推送到 ReactJS 中的数组中
2021-12-28
13524
我遇到以下情况。我正在从后端获取数据,响应是一堆对象。我想迭代它们,并在每次迭代中将它们推送到我的状态中。
这是我从后端获取数据的方式:
const allBookings = useSelector(getBookings);
useEffect(() => {
dispatch(
fetchBookings.request({
getAll: true,
})
);
}, [dispatch]);
这是我的数据:
bookings:{
0:{id: 294, address: '1585 Charleston Rd, Mountain View, CA, USA', broker:{name:'aaa'}},
1:{id: 294, address: '1586 Charleston Rd, Mountain View, CA, USA', broker:{name:'bbb'}},
2:{id: 294, address: '1587 Charleston Rd, Mountain View, CA, USA', broker:{name:'ccc'}}
}
在这里,我试图将我的数据设置为数组,但出现问题,请帮助我弄清楚如何实现。最终结果应该是这样的:
[
{id: 294, address: '1585 Charleston Rd, Mountain View, CA, USA', broker:{name:'aaa'}},
{id: 294, address: '1586 Charleston Rd, Mountain View, CA, USA', broker:{name:'bbb'}},
{id: 294, address: '1587 Charleston Rd, Mountain View, CA, USA', broker:{name:'ccc'}}
]
if (!allBookings) return null;
const book = allBookings.bookings;
const [books, setBooks] = useState([]);
useEffect(() => {
if (book) {
const x = Object.entries(book);
setBooks(x);
}
}, [book]);
console.log('books===>', books);
3个回答
使用功能更新将新条目推送到您的
books
数组中:
const x = Object.entries(book);
setBooks(books => [...books, ...x]);
由于您始终使用空数组实例化,因此您也不需要进行错误检查,即您可以删除
if (books)
。
Terry
2021-12-28
将
const x = Object.entries(book)
; 更改为
const x = Object.values(book);
sandeep.kgp
2021-12-28
在您的
useEffect
中使用商店选择器 var 来监视更改,
此外,您不应该在您的例子中使用 Object.entries ,而是使用 Object.values ,
Object.entries 将获取键和值,并将它们作为每个条目的数组,如
[["0",{id: 294, address: '1585 Charleston Rd,...}]]
但
Object.values
只会从值(您的对象)创建新数组
您的代码应该看起来喜欢
const [books, setBooks] = useState([]);
useEffect(() => {
if (allBookings.bookings) {
const entries = Object.values(allBookings.bookings);
setBooks(entries);
}
}, [allBookings]);
尝试下面的代码片段:
// Get a hook function
const {useState, useEffect } = React;
const Example = ({title}) => {
let serverObject = {
bookings:{
0:{id: 294, address: '1585 Charleston Rd, Mountain View, CA, USA', broker:{name:'aaa'}},
1:{id: 294, address: '1586 Charleston Rd, Mountain View, CA, USA', broker:{name:'bbb'}},
2:{id: 294, address: '1587 Charleston Rd, Mountain View, CA, USA', broker:{name:'ccc'}}
}
}
const [allBookings, setAllBookings] = useState({});
const [books, setBooks] = useState([]);
setTimeout(()=> { setAllBookings(serverObject)}, 2000)
useEffect(() => {
if (allBookings.bookings) {
const entries = Object.values(allBookings.bookings);
setBooks(entries);
}
}, [allBookings]);
return (
<div>
{
books.map( book => <p> {book.address} </p>)
}
</div>
);
};
// Render it
ReactDOM.render(
<Example title="Example using Hooks:" />,
document.getElementById("app")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<div id="app"></div>
Bourbia Brahim
2021-12-28