Ed *_*ght 1 reactjs react-hooks
我正在尝试使用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>
);
};
Run Code Online (Sandbox Code Playgroud)
您还可以通过以下网址查看此[不]工作:https : //codesandbox.io/s/p3n327zn3q
是否有人对handleSubmit函数中的setArray为什么不自动导致组件重新呈现有任何建议?
小智 5
Instead of
let updateArray = array;
Run Code Online (Sandbox Code Playgroud)
Try this:
const updateArray = [...array];
Run Code Online (Sandbox Code Playgroud)
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.
小智 5
类似的错误可能会以相同的表现形式发生:
const [bought, setBought] = useState([])
...
bought.push(newItem)
setBought(bought)
Run Code Online (Sandbox Code Playgroud)
要解决此问题,您需要使用
const newBought = [...bought, newItem] <- new reference
setBought(newBought)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1202 次 |
| 最近记录: |