在组件外部使用 redux 挂钩以实现代码可重用性



我有一个功能组件如下,我有一个有两个调度的函数。一个设置错误消息,另一个在短暂的超时后删除错误消息。设置错误和清除的功能来自许多其他组件,因此我希望在另一个文件中拥有两个调度函数以允许代码可重用性。我无法执行此操作,因为我收到一个错误,说我只能在功能组件中使用useDispatch。我该如何克服这个问题?

组件

const Checkout = () => {
const dispatch = useDispatch();
const setErrors = (payload) => {
dispatch({
type: 'SET_ERRORS',
payload,
});
setTimeout(() => {
dispatch({
type: 'CLEAR_ERRORS',
});
}, 2500);
};
return (
<>
// JSX stuff come here
<>
)
}

减速机

const initialState = {
message: null,
status: false,
};
export default (state = initialState, action) => {
switch (action.type) {
case 'SET_ERRORS':
return {
...state,
message: action.payload,
status: true,
};
case 'CLEAR_ERRORS':
return {
...state,
message: null,
status: false,
};
default:
return state;
}
};

使用钩子更新2021

在组件外部使用useDispatch将导致错误。

首先,从 Redux 导入常规store,然后使用 dispatch 方法。 例如:

import store from 'YOUR_DESTINATION_TO_REDUX_STORE'
function doSomething() {
// do your stuff

store.dispatch(YOUR_ACTION())
}

您可以创建自己的自定义钩子,例如useErrorDispatcher,并在许多功能组件中使用它。另请注意,钩子只允许在功能组件中使用。

export const useErrorDispatcher = () => {
const dispatch = useDispatch();
return (payload) => {
dispatch({ type: 'SET_ERRORS', payload});
setTimeout(() => dispatch({type: 'CLEAR_ERRORS'}), 2500);
}
}

用法:

const MyComponent = (props) => {
const errorDispatcher = useErrorDispatcher();
return (
<button onClick={() => errorDispatcher('an error occurred')} />
);
}
const setErrors = (payload, dispatch) => {}

修改setErrors函数以dispatch获取附加参数。现在,您应该能够在许多组件中重用setErrors

最新更新