我在这里定义了几个输入字段和一些初始值:
const initialValues = {
projectName: '',
cabinetType: '',
cabinetWidth: '',
cabinetDepth: '',
};
在函数中,我使用从输入字段调用的
handleInputChange
方法处理输入,效果很好:
const [values, setValues] = useState(initialValues);
const handleInputChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
};
当我尝试有条件地设置
cabinetDepth
的值时,我遇到的问题是:
const handleInputChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
if(values.cabinetType === "kitchen_base"){
setValues({
...values,
["cabinetDepth"]: "24",
});
}
};
这行不通。什么也没发生。
我的解决方法是让 CabinetDepth 在值数组之外拥有自己的常量和自己的
handleCabinetDepth
函数,如下所示,但是当您必须对多个字段多次执行此操作时,这很麻烦:
const [cabinetDepth, setCabinetDepth] = useState('');
const handleCabinetDepth = (e) => {
setCabinetDepth(e.target.value);
}
我认为你不能有条件地调用反应钩子。至少我上次使用 React 时是这样。我记得每次渲染时所有钩子都必须被调用相同的次数,这意味着在条件表达式中调用设置状态会导致不可预测的行为,并且不应该真正执行。
您可以使用功能设置器来移动设置状态函数调用内的条件逻辑来更新状态。
setValues((values) => {
if (values.cabinetType === "kitchen_base") {
return { ...values, ["cabinetDepth"]: "24" };
}
return values
});
这样,钩子仍然会被一致地调用,但您仍然可以根据您拥有的任何其他值来表达更新值所需的任何逻辑。