我的减速机:
export const initialUserState = {
username: '',
address: '',
token: '',
address: '',
loggedIn: false,
loaded: false,
};
export const userReducer = async (state, action) => {
try {
switch (action.type) {
case 'LOAD':
try {
const value = JSON.parse(await AsyncStorage.getItem('user_info'));
const newState = { ...state, ...value, loggedIn: true, loaded: true };
console.log('New State:', newState);
if (value !== null) {
return newState;
}
} catch (error) {
return { ...state, loaded: true };
}
break;
default:
return state;
}
} catch (error) {
console.log(error);
return state;
}
};
我的 App.js:
import { userReducer, initialUserState } from './reducer';
const App = () => {
const [user, dispatch] = useReducer(userReducer, initialUserState);
useEffect(() => {
dispatch({ type: 'LOAD', ready: setReady });
}, []);
useEffect(() => {
console.log('state user:', user);
}, [user]);
}
export default App;
发生的情况是,在 App.js 中,在调用第二个 useEffect 之后,状态更新并且用户返回一个 Promise。承诺有多个属性,其中一个是它应该返回的正确状态。它不应该返回状态吗?难道我做错了什么?
简而言之:
1) 应用程序启动
2)useEffect第一次调用并具有正确的初始状态
3) 我调用 LOAD 动作来更新状态
4) useEffect 被第二次调用。这次它返回一个承诺,我猜它应该只返回商店的更新状态?