Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.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
Reactjs 我试图将数据推入react中useState中定义的数组,但数据并没有被推入数组_Reactjs_React Hooks - Fatal编程技术网

Reactjs 我试图将数据推入react中useState中定义的数组,但数据并没有被推入数组

Reactjs 我试图将数据推入react中useState中定义的数组,但数据并没有被推入数组,reactjs,react-hooks,Reactjs,React Hooks,我试图将一些数据推送到useState中定义的数组中,但数据没有被推送到数组中 //下面是代码 const [formData, setFormData] = useState({ name: "", technology: [], description: "", technoText: '' }); const { name, description, technoText, technology } = formD

我试图将一些数据推送到useState中定义的数组中,但数据没有被推送到数组中

//下面是代码

 const [formData, setFormData] = useState({
        name: "",
        technology: [],
        description: "",
        technoText: ''
    });

const { name, description, technoText, technology } = formData;
    const onChange = e => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

const onAdd = (e) => {
    e = e || window.event;
    const newElement = { id: uuid.v4(), value: technoText }
    if(e.keyCode === 13){
        setFormData({...formData, technology: currentArray => [...currentArray, newElement]});
        console.log(newElement);
        console.log('this is technology', technology)
    }
}

//newElement的数据正在控制台中记录,但未在阵列技术中推送。

技术
键设置为
阵列
,而不是函数或使用函数
使用状态

const [formData, setFormData] = useState({
  technology: []
});

const { name, description, technoText, technology } = formData;

const onChange = e => {
  setFormData({ ...formData, [e.target.name]: e.target.value });
};


const onAdd = e => {
  e = e || window.event;
  const newElement = { id: uuid.v4(), value: technoText };
  if (e.keyCode === 13) {

    setFormData({ ...formData, technology: [...technology, newElement] });

    // v You defined the `technology`'s value as a function
    // setFormData({...formData, technology: currentArray => [...currentArray, newElement]});

    // I think you ment using a functional useState like so:
    setFormData(prevState => ({
      ...formData,
      technology: [...prevState.technology, newElement]
    }));

    // Or more like
    setFormData(({ technology: currentArray }) => ({
      ...formData,
      technology: [...currentArray, newElement]
    }));
  }
};

什么?更改注释中提到的
currentArray=>[…currentArray,newElement]}