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 => {
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>
);
};
您还可以看到这个 [not] 工作于:
https://codesandbox.io/s/p3n327zn3q
关于为什么 handleSubmit 函数中的 setArray 没有自动导致组件重新渲染,有人有什么建议吗?
而不是
let updateArray = array;
试试这个:
const updateArray = [...array];
https://codesandbox.io/embed/qxk4k3zmzq
因为JS中的数组是引用值,所以当你尝试使用=复制它时,它只会复制对原始数组的引用。
类似的错误可能会发生在相同的表现形式上:
const [bought, setBought] = useState([])
...
bought.push(newItem)
setBought(bought)
要解决此问题,您需要使用
const newBought = [...bought, newItem] <- new reference
setBought(newBought)
我正在尝试使用 React Hooks 和表单更新 UI。我有一个状态集来监视表单上的值,当我单击提交时,我想将该值添加到一个数组(保存在状态中)并将其显示在 UI 上。我的问题是,当我提交该值时,尽管它已添加到数组中(并且状态已更新),但 UI 仅在我更改输入中的值时更新。
我的组件如下:
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>
);
};
您还可以看到这个 [not] 工作于: https://codesandbox.io/s/p3n327zn3q
关于为什么 handleSubmit 函数中的 setArray 没有自动导致组件重新渲染,有人有什么建议吗?
而不是
let updateArray = array;
试试这个:
const updateArray = [...array];
https://codesandbox.io/embed/qxk4k3zmzq
因为JS中的数组是引用值,所以当你尝试使用=复制它时,它只会复制对原始数组的引用。
类似的错误可能会发生在相同的表现形式上:
const [bought, setBought] = useState([])
...
bought.push(newItem)
setBought(bought)
要解决此问题,您需要使用
const newBought = [...bought, newItem] <- new reference
setBought(newBought)