[英]Input field value is not updating in React form
I am creating some input fields dynamically in react but once I update the value, it doesn't update in the input field and show the previous value.我在反应中动态创建了一些输入字段,但是一旦我更新了值,它就不会在输入字段中更新并显示以前的值。
const Content = input => {
const [inputList, setInputList] = useState({}); // it is initialized in other function with some dynamic keys:
const getFiltersValues = filters => {
let data = {};
for (let i = 0; i < filters.length; i++) {
data[filters[i]] = [];
}
// ... some other processing which stores the data in data object against each key
let list = {};
for (const [key, values] of Object.entries(data)) {
list[`${key}a`] = 0;
list[`${key}b`] = 0; // key is something like 'data size'
}
setInputList(list);
};
// setting up value like this:
const handleChange = (e, field) => {
const list = inputList;
list[`${field}a`] = parseInt(e.target.value);
setInputList(list);
};
// rendering input fields:
return (
<>
{filters && filters.length > 0 && (
<div>
{filters.map(f => {
return (
<div>
// correct updated value is shown on the console but its not updated in the 'value' attribute
{console.log(inputList[`${f.value}a`])}
<input
value={inputList[`${f.value}a`] || 0}
type="number"
onChange={e => handleChange(e, f.value)}
/>
</div>
</div>
);
})}
</div>
)}
</>
);
};
Any suggestions/hints where I am getting wrong?我出错的任何建议/提示? Thank you.
谢谢你。
It was a mistake while updating the object.更新 object 时出错。 It should have done in this way:
它应该以这种方式完成:
const handleChange = (e, field) => {
const list = {...inputList};
list[`${field}a`] = parseInt(e.target.value);
setInputList(list);
};
First copy the inputList
to list
and then update it and set again.首先将
inputList
复制到list
,然后对其进行更新并重新设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.