Reactjs 通过localStorage在reducer中填充initialState
我有一个react/redux应用程序,我需要首先使用localStorage从state填充一个道具 我想用这样的东西做Reactjs 通过localStorage在reducer中填充initialState,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我有一个react/redux应用程序,我需要首先使用localStorage从state填充一个道具 我想用这样的东西做 const initialState = (() => { let username = window.localStorage.getItem('username'); if (!username) { username = ''; } return { username: username }; })(); 我听说用逻辑将in
const initialState = (() => {
let username = window.localStorage.getItem('username');
if (!username) {
username = '';
}
return {
username: username
};
})();
我听说用逻辑将initialState复杂化并不是一个很好的做法,但我还没有找到任何其他方法
是否有更清晰的解决方法?您可以使用默认函数参数来定义减速器本身的初始状态,就像这样,只需使用or运算符即可。用户的初始状态将首先在本地存储中检查,如果为null,则为空字符串
const userReducer = ( state = window.localStorage.getItem("username") || "", action ) => {
/*
* some logic to handle actions
*
*/
return state;
};
希望这有帮助 对于延迟加载初始值设定项函数来说,这似乎是一个完全可以接受的用例。我不知道为什么这会被认为是一种不好的做法。