我有两个函数,我想调用useEffect Hook,但它抱怨。
警告:组件正在将受控输入更改为不受控制。这可能是由于值从已定义更改为未定义而导致的,这不应该发生。决定在组件的生命周期内使用受控或非受控输入元素。
如何解决这个问题?谢谢。。
const product_properties_list = async () => {
const res = await axios.get('http://127.0.0.1:8000/api/admin/product_properties/product_properties_list');
setState({product_properties_list: res.data});
}
const single_property_value = async () => {
const res = await axios.get(`http://127.0.0.1:8000/api/admin/property_values/property_values_edit/${id}`)
setState({
property_values_name: res.data.property_values_name,
validator: [],
message:''
});
}
useEffect(() => {
product_properties_list();
single_property_value();
}, [])
JSX 代码
return (
<>
<div className="container text-center mt-5">
<form className="fff" onSubmit={property_values_edit}>
<div className="border border-success col-4 offset-4 p-1">
<div className="mb-3 form-floating text-left">
<select name="product_properties_id" onChange={handleInput} className="form-control" required>
<option value="0">SELECT</option>
{state.product_properties_list.map(product_properties_single => (
<option key={product_properties_single.id} value={product_properties_single.id}>{product_properties_single.product_properties_name}</option>
))}
</select>
</div>
<div className="mb-3 form-floating text-left">
<input name="property_values_name" value={state.property_values_name} onChange={handleInput} type="text" className="form-control" id="property_values_name" required />
<label htmlFor="property_values_name">Property Values Name:</label>
</div>
<div className="form-floating">
<button className="btn btn-md btn-primary col-12" type="submit">Property Values Update</button>
</div>
</div>
</form>
</div>
</>
);
输入字段value
最初定义,后来设置为undefined
。 您正在状态对象中设置property_values_name
属性 通过执行setState({product_properties_list: res.data});
来undefined
,即用{product_properties_list: res.data}
替换整个状态。
const product_properties_list = async () => {
const res = await axios.get('http://127.0.0.1:8000/api/admin/product_properties/product_properties_list');
setState(currState => ({...currState, product_properties_list: res.data}));
}
从当前状态setState
,这样您就不会将property_values_name
设置为undefined