Javascript React native redux-this.props未从异步存储中定义
作为一个使用RN和Redux的新手,我很困惑为什么在阅读AsyncStorage之后我的道具没有定义 我登录,将状态保存到存储和存储。。。我重新加载应用程序,从存储器中读取并更新状态。存储正在检索我的对象,但道具未定义 actions.js:Javascript React native redux-this.props未从异步存储中定义,javascript,react-native,react-redux,redux-thunk,Javascript,React Native,React Redux,Redux Thunk,作为一个使用RN和Redux的新手,我很困惑为什么在阅读AsyncStorage之后我的道具没有定义 我登录,将状态保存到存储和存储。。。我重新加载应用程序,从存储器中读取并更新状态。存储正在检索我的对象,但道具未定义 actions.js: export const getSession = (data) => ({ type: 'GET_SESSION', payload: { user: data } }); export const get
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的用户。所以改变 常量mapStateToProps=状态=>{ 用户:state.user, }; 到 常量mapStateToProps=状态=>{ 用户:state.authReducer.user, }; 还有一件事,AsyncStorage的getItem方法返回存储数据的字符串。您尚未将其转换为json。因此,也请将其转换为以下内容: export const getUserSession==>dispatch=>{ 返回AsyncStorage.getItem'userSession'。然后返回数据=>{ console.log'Props at asynsstorage:',数据; //{当前用户:{uid:1,角色:[已验证,管理员],…} 调度加载错误; dispatchgetSessionJSON.parsedata;//在此处转换为json } .catcherr=>{ } }
为什么要从AsyncStorage读取值,为什么不从props读取值?添加Wait和async,如下所示:感谢您的警告;我已经对对象进行了字符串化和解析,只是为了简单起见将其删除了。state.authReducer.user做到了这一点。谢谢。