作为 RN
和 Redux
的新手,我很困惑为什么在读取 AsyncStorage
后我的 props 未定义。
我登录,将状态保存到商店和存储中...我重新加载应用程序并从存储中读取并更新状态。存储正在检索我的对象,但 Prop 未定义。
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,
});
还有一件事,AsyncStorage
的 getItem()
方法返回存储数据的字符串。你还没有转换成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) => {
})
}
关于javascript - React-native redux - this.props 未从 AsyncStorage 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59218056/