我在Redux上使用React,并具有以下代码:
hooks.js
:
import { useDispatch } from 'react-redux';
import { checkCookieOne, checkCookieTwo } from './thunk';
...
export function useValidateCookieEffect() {
const dispatch = useDispatch();
React.useEffect(() => {
dispatch(checkCookieOne());
dispatch(checkCookieTwo());
}, [dispatch]);
}
并且在我的thunk
文件中:
export function checkCookieOne() {
return async dispatch => {
const hasCookie = Boolean(window.localStorage.getItem('cookieOne') || false);
dispatch(store.actions.toggleCookieOneValue(hasCookie));
};
}
export function checkCookieTwo() {
return async dispatch => {
const hasCookie = Boolean(window.localStorage.getItem('cookieTwo') || false);
dispatch(store.actions.toggleCookieTwoValue(hasCookie));
};
}
为了使其更具可读性,我想将代码合并为单行返回。
所以,来自:
export function checkCookieOne() {
return async dispatch => {
const hasCookie = Boolean(window.localStorage.getItem('cookieOne') || false);
dispatch(store.actions.toggleCookieOneValue(hasCookie));
};
}
对于这样的事情(我的尝试)-请记住,dispatch
没有在此文件中声明,而仅在hooks.js
中声明:
export async function checkCookieOne() => dispatch(store.actions.toggleCookieOneValue(checkGivenCookieExists('cookieOne')));
但是那是无效的语法。它抱怨箭头功能,说:
'{'或';'预期。
如何将其转换为一行?
export function checkCookieOne() { return async dispatch => dispatch(store.actions.toggleCookieOneValue(checkGivenCookieExists('cookieOne'))); }
这可以用,但不完全是我想要的
尝试一下
let checkCookieOne = async () => dispatch(store.actions.toggleMyCookieValue(checkGivenCookieExists('cookieOne')));
export checkCookieOne;
// Or maybe...
export let checkCookieOne = async () => dispatch(store.actions.toggleMyCookieValue(checkGivenCookieExists('cookieOne')));