我正在尝试将数据推送到react中useState中定义的数组中,但是没有将数据推送到数组中

时间:2019-10-06 06:08:21

标签: reactjs react-hooks

我正在尝试将一些数据推送到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的数据正在控制台中记录,但没有被阵列技术推送。

1 个答案:

答案 0 :(得分:1)

technology键设置为Array而非功能或使用功能性useState

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]
    }));
  }
};