React-native redux - this.props 未从 AsyncStorage 定义

React-native redux - this.props are undefined from AsyncStorage

作为 RNRedux 的新手,在阅读 AsyncStorage.

后,我很困惑为什么我的道具未定义

我登录,将状态保存到存储和存储...我重新加载应用程序并从存储中读取并更新状态。存储正在检索我的对象,但道具未定义。

actions.js:

export const getSession = (data) => ({
    type: 'GET_SESSION',
    payload: {
        user: data
    }
});

export const getUserSession = () => dispatch => {
    return AsyncStorage.getItem('userSession').then((data) => {
        console.log('Props at asynsstorage: ', data);
        // {"current_user":{"uid":"1","roles":["authenticated","administrator"], ...}
        dispatch(loading(false));
        dispatch(getSession(data));
    })
    .catch((err) => {
    })
}

reducer.js

import { combineReducers } from 'redux';

const defaultState = {
    xcsrf: '',
    user: {},
    loading: false,
    error: '',
};

const authReducer = ( state = defaultState, action ) => {
    switch(action.type) {
        case 'GET_SESSION':
            return {
            ...state,
                user: action.payload.user,
                loading: false,
            }

        case 'SAVE_SESSION':
            return {
                ...state,
                user: action.payload.user,
                loading: false,
            }

        default:
            return state;
    }
}

export default combineReducers({
    authReducer: authReducer
});

authLoading.js // 屏幕

class AuthLoadingScreen extends React.Component {
    constructor() {
        super();
    }

    componentDidMount = () => {
        this.props.getUserSession().then(() => {
            console.log( 'Props at loading: ', this.props.user );
            // undefined

        })
        .catch(error => {
        })
    };

    // Render any loading content that you like here
    render() {
        return ();
    }
}

const mapStateToProps = state => ({
    user: state.user,
});


const mapDispatchToProps = dispatch => ({
    getUserSession: () => dispatch(getUserSession()),
});

export default connect(mapStateToProps, mapDispatchToProps)(AuthLoadingScreen);

你不能直接访问reducer的user。所以改变

const mapStateToProps = state => ({
    user: state.user,
});

const mapStateToProps = state => ({
    user: state.authReducer.user,
});

还有一件事 AsyncStoragegetItem() 方法 return 存储数据的字符串。你还没有转换成它 json。所以也请将其转换如下:

export const getUserSession = () => dispatch => {
    return AsyncStorage.getItem('userSession').then((data) => {
        console.log('Props at asynsstorage: ', data);
        // {"current_user":{"uid":"1","roles":["authenticated","administrator"], ...}
        dispatch(loading(false));
        dispatch(getSession(JSON.parse(data))); //convert to json here
    })
    .catch((err) => {
    })
}