【问题标题】:How to update a Textfield that has a value from an array of objects state variable in React?如何更新具有来自 React 中对象状态变量数组的值的文本字段?
【发布时间】:2020-05-28 13:31:43
【问题描述】:

在反应中,我试图用设置为对象值的值更新 Textfields 中渲染的映射对象数组,然后还能够更新/更改 Textfield 中的值和相应的状态值。当前,对象数组已正确映射并使用对象值显示,但是当尝试更改 TextField 中的值时,显示中没有任何变化,控制台日志仅导致更改值的最后一个字母。似乎因为我需要 Textfield 以一个值开头,该值保留旧值,因为数据是用地图呈现的,或者我是否错误地更新了对象数组?尽管在此示例中不需要对象数组,但它适用于确实需要它的组件。

以下是一些示例代码来演示:

import React, { useState} from 'react';

const Test = () => {
  const [data, setData] = useState([
    {
      num: 1,
      name: 'hello'
    },
    {
      num: 2, 
      name: 'world'
    },
    {
      num: 3,
      name: 'test'
    },
  ]);

const handleChange = e => {
    const { name, value, id } = e.target;
    setData(data[id].name = value)
    console.log(value)
}

return (
    <div>
        {
          data.map((_itm, index) => (
            <TextField key={index} value={_itm.name} onChange={handleChange} name='name' id={index.toString()}/>
          ))
        }
      </div>
)
}

因此将显示 3 个文本字段,其中包含值、hello、world 和 test。尝试编辑文本字段时,值不会更改。 感谢您提供任何和所有帮助,谢谢。

【问题讨论】:

    标签: arrays reactjs object state


    【解决方案1】:

    在状态钩子中,data 被设置为一个数组。因此,无论何时调用 setData,您都应该始终传递该数组的更新副本。

    const handleChange = e => {
        const { value, id } = e.target;
    
        // Make a shallow copy of the current `data`.
        const newArray = [...data];
    
        // Update the changed item.
        newArray[id] = {
            ...newArray[id],
            name: value
        }
    
        // Call setData to update.
        setData(newArray);
        console.log(value);
    }
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,上面的代码不起作用。我做的有点不同,写了一个 100% 工作的代码,不管你如何命名对象中的键

      const changeHandler = (e) => {
          const { id, name, value } = e.target
          const newArray = [...data]
          newArray[id][name] = value
      
          setForm(newArray)
      
      } 
      
       
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-12
        • 2019-05-07
        • 2019-09-23
        • 1970-01-01
        相关资源
        最近更新 更多