UI 不会使用 React Hooks 和表单提交重新渲染状态更新 [英] UI not re-rendering on state update using React Hooks and form submission
问题描述
我正在尝试使用 React Hooks 和表单更新 UI.我有一个状态设置来监视表单上的值,当我单击提交时,我想将此值添加到一个数组(保持状态)并将其显示在 UI 上.我的问题是,当我提交值时,虽然它被添加到数组中(并且状态已更新),但 UI 仅在我更改输入中的值时更新.
我的组件如下:
const PushToArrayUpdateState = () =>{const [array, setArray] = useState([]);const [formVal, setFormVal] = useState(``);const handleSubmit = 事件 =>{event.preventDefault();让 updateArray = 数组;updateArray.push(formVal);控制台日志(更新数组);设置数组(更新数组);};返回 (<div><form onSubmit={handleSubmit}><input type="text" name="arrayVal" onChange={e =>setFormVal(e.target.value)}/><input type="submit" value="Submit"/></表单><div>{array.map((val, index) => <p key={index}>{val}</p>)}
);};
你也可以看到这个 [not] 工作于:https://codesandbox.io/s/p3n327zn3q
有没有人对为什么 handleSubmit 函数中的 setArray 没有自动导致组件重新渲染有任何建议?
代替
let updateArray = array;
试试这个:
const updateArray = [...array];
https://codesandbox.io/embed/qxk4k3zmzq
因为 JS 中的数组是引用值,所以当你尝试使用 = 复制它时,它只会复制对原始数组的引用.
I'm trying to update a UI using React Hooks and a form. I have a state set to monitor the value on the form and when I click submit, I want to add this value to an array (held in state) and display it on the UI. My problem is that when I submit the value, although it is added to the array (and state is updated), the UI only updates when I change the value in the input.
My Component is as follows:
const PushToArrayUpdateState = () => {
const [array, setArray] = useState([]);
const [formVal, setFormVal] = useState(``);
const handleSubmit = event => {
event.preventDefault();
let updateArray = array;
updateArray.push(formVal);
console.log(updateArray);
setArray(updateArray);
};
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" name="arrayVal" onChange={e => setFormVal(e.target.value)} />
<input type="submit" value="Submit" />
</form>
<div>
{array.map((val, index) => <p key={index}>{val}</p>)}
</div>
</div>
);
};
You can also see this [not] working at: https://codesandbox.io/s/p3n327zn3q
Has anyone got any suggestions as to why the setArray in the handleSubmit function is not automatically causing the component to re-render?
Instead of
let updateArray = array;
Try this:
const updateArray = [...array];
https://codesandbox.io/embed/qxk4k3zmzq
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array.
这篇关于UI 不会使用 React Hooks 和表单提交重新渲染状态更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!