React-Native Redux-AsyncStorage中未定义this.props

时间:2019-12-06 17:50:55

标签: javascript react-native react-redux redux-thunk

作为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);

1 个答案:

答案 0 :(得分:1)

您不能直接访问减速器的user。因此,更改

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

收件人

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

AsyncStorage的{​​{1}}方法又返回了存储数据的字符串。您尚未将其转换为json。因此,请按如下所示进行转换:

getItem()