Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 使用React钩子向对象内的数组添加数据_Arrays_Reactjs_Immutability_React Hooks - Fatal编程技术网

Arrays 使用React钩子向对象内的数组添加数据

Arrays 使用React钩子向对象内的数组添加数据,arrays,reactjs,immutability,react-hooks,Arrays,Reactjs,Immutability,React Hooks,我不知道如何在React中使用setState by hook将数组数据添加到对象内的数组列表中。有人能帮我吗? 下面是我的代码,每次我登录控制台时,它总是返回空数组 import React, { useState } from 'react'; const Main = props => { const [state, setState] = useState({ noteArray: [], noteText: '', }); const addNo

我不知道如何在React中使用setState by hook将数组数据添加到对象内的数组列表中。有人能帮我吗? 下面是我的代码,每次我登录控制台时,它总是返回空数组

import React, { useState } from 'react';

const Main = props => {
  const [state, setState] = useState({
    noteArray: [],
    noteText: '',
  });


  const addNote = () => {
    if(state.noteText){
      var d = new Date();
      let x = {
        'date': d.getFullYear() + 
        "/" + (d.getMonth() + 1 ) +
        "/" + d.getDate(),
        'note': state.noteText
      }

      setState({...state, noteArray: x});

      console.log(state.noteArray);
    }
  }

   .......................the rest of code
}

基本上,您所做的错误是覆盖了您的数组,而不是向其添加新的值。您可以使用以下方法轻松完成此操作:-

import React, { useState } from 'react';

const Main = props => {
  const [state, setState] = useState({
    noteArray: [],
    noteText: '',
  });


  const addNote = () => {
    if(state.noteText){
      var d = new Date();
      let x = {
        'date': d.getFullYear() + 
        "/" + (d.getMonth() + 1 ) +
        "/" + d.getDate(),
        'note': state.noteText
      }

      setState({...state, noteArray: [...state.noteArray, x]});

      console.log(state.noteArray);
    }
  }

   .......................the rest of code
}

你的代码,陷入无限循环,下面是你的代码one@ukiyakimura你是想重置你的数组还是想添加到数组中?@solanki。。。你能解释一下这将如何进入一个无限循环吗?已经在本地测试过了,我正在尝试将其附加到@yashgadle上。我如何使用setState?强制状态立即更新,它仍然不会更改值,直到组件首先被重新渲染@亚什·盖德尔