[英]Using redux hooks outside of a component for code reusability
我有一個功能組件如下,我有一個有兩個分派的功能。 一個設置錯誤消息,另一個在短暫的超時時間后刪除錯誤消息。 設置錯誤和清除的功能存在於許多其他組件中,因此我希望在另一個文件中具有兩個調度函數以允許代碼重用。 我無法做到這一點,因為我收到一個錯誤,說我只能在功能組件中使用 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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.