React JS:数组未传递给状态
React JS: Array is not being passed to state
我有一个名为 'array' 的对象数组。当我尝试将它传递给 useState '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;
map
不是正确的方法。
使用 forEach
或 for
循环代替它。
试试这个:
array.forEach(row => {
setRows(rows => [...rows, row]);
});
以下文档将帮助您更好地理解 map
的用法。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
我有一个名为 'array' 的对象数组。当我尝试将它传递给 useState '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;
map
不是正确的方法。
使用 forEach
或 for
循环代替它。
试试这个:
array.forEach(row => {
setRows(rows => [...rows, row]);
});
以下文档将帮助您更好地理解 map
的用法。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map