【发布时间】:2020-03-31 17:41:33
【问题描述】:
作为RN 和Redux 的新手,我很困惑为什么在阅读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);
【问题讨论】:
-
你为什么从 AsyncStorage 中读取值,为什么不从 props 中读取呢?
-
添加等待和异步,如下所示:stackoverflow.com/questions/37120305/…
标签: javascript react-native react-redux redux-thunk