我在使用React Hooks重新填充编辑表单时遇到了问题。
父组件:Edit.js
const EditData = (props) => {
const { Id } = props.match.params;
const dispatch = useDispatch();
// calling redux action to get the data
useEffect(() => {
dispatch(getDataById(Id));
}, [Id]);
const data = useSelector((state) => state.data);
const initialState = {
Id: data.cardId || '',
Number: data.Number || '',
Date: data.Date,
};
//calling custom hook
const { handleChange, handleSubmit, values,errors } = useForm(
initialState,// passing initial state to custom hook
validateOnSubmit,
submit
);
// used to submit the data
function submit() {
dispatch(updateCard(values));
}
return (<DateForm
handleSubmit={handleSubmit}
handleChange={handleChange}
values={values}
/>);
};
自定义钩子:useform.js
const useForm = (initialState, validateOnSubmit, callback) => {
const [values, setValues] = useState(initialState);
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const handleChange = (event) => {
const { name, value } = event.target;
setValues({
...values,
[name]: value
});
};
const handleSubmit = (event) => {
event.preventDefault();
setErrors(validateOnSubmit(values));
setIsSubmitting(true);
};
useEffect(() => {
if (Object.keys(errors).length === 0 && isSubmitting) {
callback();
}
}, [errors]);
return {
handleChange,
handleSubmit,
values,
errors
};
};
当API调用完成时,React会重新渲染组件,但是钩子的本地状态不会更新。
const useForm = (initialState, validateOnSubmit, callback) => {
console.log(initialState);
在第二次渲染时,我可以从API接收数据。
const [values, setValues] = useState(initialState);
但是values没有更新,values仍然保持初始渲染时的状态。
我无法弄清原因。我刚开始使用react hooks,请帮助我。
initialState
被更新了但values
没有被更新? - Dennis VashinitialState
变量在API调用完成时会更新,我将该initialState
变量传递给const [values,setValues] = useState(initialState);
,所以它应该更新values
变量,但实际上并没有! - p6aveen