当我键入input并进行更改编辑时,hours不会更新输入值,但我会在控制台中看到更新的值。
OpenSSH_7.2p2 Ubuntu-4ubuntu2.8, OpenSSL 1.0.2g 1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "ip-172-31-43-162.us-east-2.compute.internal" port 22
ssh: Could not resolve hostname ip-172-31-43-162.us-east-2.compute.internal: Name or service not known
答案 0 :(得分:3)
在React中,您应该避免进行状态更改,这意味着不要显式更改属于现有状态的内容。为了让React决定是否重新渲染以反映您的更改,它需要注册一个新状态。
养成创建状态的克隆或深层副本,然后进行更新的好习惯。
尝试类似这样的方法。在下面,我们使用传播运算符{...}
在更新状态之前先对其进行克隆:
const nullableEntry = {
ID: "",
day: "",
hours: 0.0,
note: ""
};
const MonthTable = props => {
const [editing, setEditing] = useState(nullableEntry);
function handleHoursInput(e) {
let newEdit = { ...editing };
newEdit.hours = e.target.value;
setEditing(newEdit);
}
return (
<input
type="number"
value={editing.hours}
step="0.01"
onChange={handleHoursInput}
className="form-control"
name=""
/>
);
};
答案 1 :(得分:3)
请勿更改状态,editing.hours = e.target.value
会更改原始状态
将您的handleHoursInput
函数更改为类似的内容
function handleHoursInput(e) {
let hours = e.target.value;
setEditing({...editing, hours});
}
答案 2 :(得分:0)
您可以通过这种方式更新功能组件中的状态
const [show, setShow] = useState(false)
const [scopesData, setScopesData] = useState(scopes)
const submitCallBack = (data) => {
setShowhowAlert(true)
setScopesData(...scopes, scopes.push({
id: generateKeyHash(),
title: data.data.scopetitle,
}))
}
这三行代码可以正确更新状态
[setScopesData(...scopes, scopes.push({
id: generateKeyHash(),
title: data.data.scopetitle,
}))