useReducer 返回一个 promise 而不是更新的状态

bru*_*o00 3 javascript reactjs react-hooks use-reducer

我的减速机:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

我的 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;
Run Code Online (Sandbox Code Playgroud)

发生的情况是,在 App.js 中,在调用第二个 useEffect 之后,状态更新并且用户返回一个 promise。承诺有多个属性,其中之一是它应该返回的正确状态。它不应该返回状态吗?难道我做错了什么?

简而言之:

1) 应用程序启动

2)useEffect第一次调用,初始状态正确

3)我调用将更新状态的 LOAD 操作

4) useEffect 第二次被调用。这次它返回一个承诺,它应该只返回商店的更新状态,我猜?

安慰

jac*_*son 6

看起来您传递给的函数useReducerasync. 所有async函数都返回一个承诺。您需要await或使用.then语法从承诺中获取值。这不是第一次通过的承诺,因为它返回初始状态。希望有帮助!