[英]State not changing after update
我在使用 state 属性组件时遇到问题,其中 state 在加载组件时不会改变。 该项目的 state 应该更改,因为我在收到上一个表单步进器中的响应后更新它,但是当我添加一个新的动态输入字段时,它会更改 state 但不是第一个
这是带来错误的代码
export default function AddProp() {
const [propertyID, setPropertyID] = useState(0);
const [step,setStep] = useState(1);
const [values,setValues] = useState({
responseMessage: "",
loading: false,
name: "",
address: "",
county: "",
city: "",
zipcode: "",
type: "",
specifictype: "",})
const [formValues, setFormValues] = useState([
{ number_of_units: "", market_rent: "", square_feet: "", beds: "", property:propertyID.property },
])
let addFormFields = () => {
setFormValues([
...formValues,
{ number_of_units: "", market_rent: "", square_feet: "", beds: "" ,property:propertyID.property},
]);
};
let sendProperties = async () => {
const response = await axios
.post(
"http://127.0.0.1:8000/property/api/v1/addProperty/",
{
property_name: values.name,
address: values.address,
county: values.county,
city: values.city,
zipcode: values.zipcode,
property_type: values.type,
},
{ headers: headers }
);
setPropertyID(response.data);
if(response.status == 200){
setStep(step + 1 );
}else{
alert("An error occurred");
}
};
switch (step) {
case 3:
return (
<PropertyType
values={formValues}
handleChange={handleFormChange}
add={addFormFields}
remove={removeFormFields}
prevStep={prevStep}
nextStep={getandSend}
/>
);
case 4:
return <Success message={"DONE"} />;
default:
}
}
不使用当前的formValues
,而是将回调传递给setFormValues
,它接受一个参数,比如currentFormValues
,并使用它来更新 state 。
const addFormFields = () => {
setFormValues(currentFormValues => [
...currentFormValues,
{ number_of_units: "", market_rent: "", square_feet: "", beds: "" ,property:propertyID.property},
]);
};
此问题与过时的 state 有关,每当我们尝试更新 state 时都会出现此问题,通常在闭包中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.