sps*_*pli 3 reactjs arrow-functions react-redux react-hooks redux-reducers
我有一个自定义钩子,它将在我的 Redux 切片“myTestSlice”中触发两个操作,action1 和 action2,在每个操作后面,我有减速器函数来获取新状态。
const useSetMyObjects = (
actions,
{ object1Name, object1Id, object2Name, object2Id }, // here throws the error cannot read property of undefined when I call the function converted from this custom hook
) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(actions.action1({ object1Name, object1Id }));
}, [object1Name, object1Id, actions, dispatch]);
useEffect(() => {
dispatch(
actions.action2({
object2Name,
object2Id
}),
);
}, [object2Name, object2Id, actions, dispatch]);
};
export default useSetMyObjects;
Run Code Online (Sandbox Code Playgroud)
我有一个反应组件,我想在数组循环和事件处理程序中使用这个自定义挂钩。因此,我必须将此自定义挂钩转换为函数才能使用它,否则我会收到警告:
React Hook“useSetMyObjects”无法在回调内调用。React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用
但我不知道如何将此自定义挂钩转换为函数。
以下是我将如何使用从自定义挂钩转换的函数:
我想在 useEffect 中使用函数 setTwoObjects:
useEffect(() => {
myData.map((data) =>
useSetMyObjects(myTestSlice.actions, {//supposed to use that converted function instead of useSetMyObjects here, but no idea how
object1Name: data.object1Name,
object1Id: data.object1Id,
object2Name: data.object2Name,
object2Id: data.object2Id
}),
);
}
}, [myData, useSetMyObjects]);
Run Code Online (Sandbox Code Playgroud)
我还在事件处理程序中使用函数 setTwoObjects:
const handleSelect = (e, value) => {
const newData = value;
useSetMyObjects(myTestSlice.actions, {//supposed to use that converted function instead of useSetMyObjects here, but no idea how
object1Name: newData.object1Name,
object1Id: newData.object1Id,
object2Name: newData.object2Name,
object2Id: newData.object2Id,
});
}
};
Run Code Online (Sandbox Code Playgroud)
如何将自定义挂钩转换为函数,以便可以在回调或事件处理程序中调用它?
Dre*_*ese 11
您希望useSetMyObjects挂钩返回一个函数,该函数接受参数并将操作包装在调用中,而不是dispatch让挂钩接受参数。
const useSetMyObjects = () => {
const dispatch = useDispatch();
const setTwoObjects = (
actions,
{ object1Name, object1Id, object2Name, object2Id },
) => {
dispatch(actions.action1({ object1Name, object1Id }));
dispatch(actions.action2({ object2Name, object2Id }));
};
return setTwoObjects;
};
Run Code Online (Sandbox Code Playgroud)
用法:
const setTwoObjects = useSetMyObjects();
Run Code Online (Sandbox Code Playgroud)
...
useEffect(() => {
myData.map((data) =>
setTwoObjects(
myTestSlice.actions,
{
object1Name: data.object1Name,
object1Id: data.object1Id,
object2Name: data.object2Name,
object2Id: data.object2Id
},
)
);
}, [myData, useSetMyObjects]);
Run Code Online (Sandbox Code Playgroud)
...
const handleSelect = (e, value) => {
const newData = value;
setTwoObjects(
myTestSlice.actions,
{
object1Name: newData.object1Name,
object1Id: newData.object1Id,
object2Name: newData.object2Name,
object2Id: newData.object2Id,
},
);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12013 次 |
| 最近记录: |