【问题标题】:I am trying to push data into array defined in useState in react, but the data is not being pushed in to array我正在尝试将数据推送到 useState 中定义的数组中,但数据没有被推送到数组中
【发布时间】:2020-02-03 20:54:21
【问题描述】:

我正在尝试将一些数据推送到 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的数据正在控制台中被记录,而不是在数组技术中被推送。

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案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]
        }));
      }
    };
    

    【讨论】:

    • 什么?我在 cmets 中提到更改 currentArray => [...currentArray, newElement]}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    相关资源
    最近更新 更多