【问题标题】:React JS: Array is not being passed to stateReact JS:数组未传递给状态
【发布时间】: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


    【解决方案1】:

    map 不是这样做的正确方法。

    使用forEachfor 循环代替它。

    试试这个:

    array.forEach(row => {
        setRows(rows => [...rows, row]);
    });
    

    以下文档将帮助您更好地了解map 的用法。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

    https://www.w3schools.com/jsref/jsref_map.asp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-18
      • 2019-05-07
      • 2019-01-20
      • 2022-01-18
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 2019-03-08
      相关资源
      最近更新 更多