![](/img/trans.png)
[英]How can I accumulate string values in useState as an array value in React?
[英]How can I store and update multiple values in React useState? if one of the value is in array?
我使用单个 useState Hook 在 React 组件中收集了一系列用户数据元素。
const [allValues, setAllValues] = useState<IProduct>({
title: '',
name: '',
category: '',
price: 0,
image: '',
size: [],
color: [],
inStock: true,
});
我们可以看到其中两个是数组。
const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
setAllValues({ ...allValues, [e.target.name]: e.target.value });
console.log(allValues);
};
和输入框是这样的......我应该做些什么改变?
<input
type='text'
className='form-control'
id='name'
name='name'
placeholder='Enter a Name'
onChange={changeHandler}
/>
setAllValues({
...allValues,
toUpdate: newValue
});
不同于
setAllValues(prev => ({
...prev,
toUpdate: newValue
}));
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.