【问题标题】:how to dynamically set an array object into input field in react如何在反应中动态地将数组对象设置为输入字段
【发布时间】:2021-09-20 13:48:42
【问题描述】:

请我尝试将数组对象动态设置为输入字段并将其发送到后端。谢谢

当我 console.log 打印输出时,它返回 undifined。 大家好,请我尝试将数组对象动态设置为输入字段并将其发送到后端。谢谢

大家好,我正在尝试将数组对象动态设置为输入字段并将其发送到后端。谢谢

const myArr= [
        {product: 'egg', price: 5, id:1},
        {product: 'cake', price: 3, id:2}
    ]

    const [input, setInput] = useState(myArr)


      const changeHandler = (id) => event => {
        const { name, value } = event.target;
        setInput(input => input.map((el) => el.id === id
          ? {
              ...el,
              [name]: value,
            }
          : el,
        ));
      };

    const submitForm = (e) =>{
        e.preventDefault();
        
        let printOut = input
            
        
        console.log({print:printOut});
        try {
            axios.post('/products/print', printOut)
        } catch (error) {
            console.log(error);
        }
    }

    return (
        <form onSubmit={submitForm}>
            {myArr.map(x=>(
                <div key={x.id}>
                    <input name='product' value= {x.product} onChange={(e) =>changeHandler(x.id)(e)}  />
                    <input name='price' value= {x.price} onChange={(e)=> changeHandler(x.id)(e)} />
                    
                </div>
            ))}
            <input type="submit" value="Submit" />
        </form>
    )

【问题讨论】:

  • 你的x.id不是未定义吗?
  • input 是一个数组,但您正试图像对象input.product 一样访问它。
  • 你的 onChange 事件应该是 'onChange={(e) => changeHander(x.I'd)(e) }' 。您的 changeHandler 返回一个函数。我认为它被称为柯里化,但它是一个返回另一个函数的函数。
  • 谢谢安迪,请问我怎样才能像数组一样访问它,我又在数据库中得到了一个空数据
  • 感谢 joseph,我已对其进行了修改,但仍然出现未定义的错误

标签: javascript reactjs


【解决方案1】:

正如我们在聊天中讨论的那样,有很多问题。

  1. handleChange 调用不正确。您的 onChange 事件应该是 onChange={(e) =&gt; changeHander(x.id)(e) } 。您的 changeHandler 返回一个函数。我认为它被称为currying,但它是一个返回另一个函数的函数。
  2. 您的setInput(input =&gt; input.map((el) =&gt; el.id === id? {...el, [name]: value,} : el,)); 也是错误的。 input.map 将永远无法工作,因为您已将其初始状态设置为 []。现在我不知道您需要什么,但是,要么将初始状态更新为 myArray,要么将 setState 映射更改为 myArray,如 setInput(input =&gt; myArray.map((el) =&gt; el.id === id? { ...el, [name]: value,} : el,));

【讨论】:

    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 2019-01-10
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2022-09-25
    • 1970-01-01
    相关资源
    最近更新 更多