请我尝试将数组对象动态设置到输入字段并将其发送到后端。谢谢
当我
console.log
打印输出时,它返回未定义。
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>
)
正如我们在聊天中讨论的那样,存在很多问题。
onChange={(e) => changeHander(x.id)(e) }
。您的 changeHandler
返回一个函数。我认为它被称为 currying
但它是一个返回另一个函数的函数。setInput(input => input.map((el) => el.id === id? {...el, [name]: value,} : el,));
也是错误的。 input.map
永远不会工作,因为您已将其初始状态设置为 []。现在我不知道你需要什么,但是,要么将初始状态更新为myArray
,要么将 setState 映射更改为 myArray,如setInput(input => myArray.map((el) => el.id === id? { ...el, [name]: value,} : el,));