【发布时间】:2021-12-01 06:05:47
【问题描述】:
我有一个名为“array”的对象数组。当我尝试将它传递给 useState 'rows' 以在我的程序中使用它时,数据不会被复制到 rows 状态并且它给了我一个空数组。
const project = () => {
const [rows, setRows] = useState([]);
const function = () => {
var array = [{username: "username1"}, {username: "username2"}];
console.log(array);
//The output here is:
//(2) [{…}, {…}]
//0: {username: 'username1'}
//1: {username: 'username2'}
//length: 2
//[[Prototype]]: Array(0)
array.map((row) => {
return setRows(rows => [...rows, row])
})
console.log(rows)
//The output here is:
//[]
//length: 0
//[[Prototype]]: Array(0)
//Another method tried
//setRows(array)
//console.log(rows)
//The output here is:
//[]
//length: 0
//[[Prototype]]: Array(0)
}
return (....);
}
export default project;
【问题讨论】:
标签: arrays reactjs axios use-state