我正在使用useReducer钩子来制作自定义的react钩子,但在我的代码下面,我无法更新我从调度器funnc接收的状



这里我想更新状态。值,因为我从输入中获得数据,我使用"名称"标记以查找要在state.value中更新的确切键。但是在我的代码中,我使用useReducer钩子在我的自定义react钩子useInput中存储状态数据。但我面临的问题是,我不能更新状态在这里,你可以看到,我从调度器函数获得数据,但我不能保存它的状态,因为我不能从减速器函数访问它。


import React from "react";
const reducer = (state, actions) => {
switch (actions.type) {
case "getData":
return {
...state,
value: { ...state.value, [actions.name]: actions.value }, // ****cannot acccess data here
};
default:
return state;
}
};
const useInput = () => {
const defaultValue = {
value: {
fullname: "",
address: "",
pincode: "",
city: "",
phone: "",
},
touch: {
fullname: false,
address: false,
pincode: false,
city: false,
phone: false,
},
};
const [state, dispatcher] = React.useReducer(reducer, defaultValue);
const getData = (e) => {
const name = e.target.name;
const value = e.target.value;
dispatcher({ type: "getData", [name]: value }); // ****heres the dispatcher function
};
//   const blurHandler = (e) => {
//     dispatcher({ type: "touch", value: true });
//   };
console.log(state.value);
return {
getData,
};
};
export default useInput;

尝试将包含namevalue属性的payload对象传递给调度函数:

const getData = (e) => {
const name = e.target.name;
const value = e.target.value;
dispatcher({ type: "getData", payload: { name, value }});
};

你可以像这样修改你的减速器来编辑相对值:

const reducer = (state, actions) => {
switch (actions.type) {
case "getData":
return {
...state,
value: { ...state.value, [actions.payload.name]: actions.payload.value }, 
};
default:
return state;
}
};

最新更新