我在使用 react Hook 重新填充表单进行编辑时遇到问题。
父组件: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}
/>);
};
自定义钩子(Hook):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 重新呈现自定义但 Hook 的本地状态未更新。
const useForm = (initialState, validateOnSubmit, callback) => {
console.log(initialState);
on second render, here i can receive data from the API
const [values, setValues] = useState(initialState);
but values is not getting updated, values is still holding the state from the initial render
我想不通这是为什么。我刚开始使用 React Hooks,请帮助我。
最佳答案
正如 OP 在评论中所述:
the initialState variable is updated when the API call get completed,I'm passing that initialState variable to const [values, setValues] =
useState(initialState);
, so it should update the values variable right?. but it's not!
应该更新状态,初始状态分配一次,直到组件卸载。
参见 useState
API , 它在 lazy initialization 中说明:
The
initialState
argument is the state used during the initial render. In subsequent renders, it is disregarded.
关于javascript - 重新渲染时 react 自定义 Hook 状态不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61101808/