我无法在Redux中使用默认状态值
你好,我有一个调度登录动作的功能,我希望首字母为false
,
但是当我将此值放入render方法时,它给了我一个错误
can't read property 'isLogin' of undefined
尽管在化简器中我添加了initialState
let initialState = {
isLogin: false,
};
const userReducer = (state = initialState, action) => {
switch (action.type) {
case IS_LOGIN:
state = {
...state,
isLogin: true,
};
break;
default:
return state;
}
return state;
};
这里的商店
const store = createStore(
combineReducers({
user: userReducer,
count: countPlayReducer,
}),
);
动作
export const isLoginFunc = isLogin => {
return {
type: IS_LOGIN,
payload: isLogin,
};
};
UI /调度
import {isLoginFunc} from '../../redux/actions/isLoginAction';
signIn = async data => {
this.setState({loading: true}); // maybe here the wrong?
API.post('/login', data)
.then(async response => {
let {
data: {
data: {
response: {token},
},
},
} = response;
this.props.dispatch(isLoginFunc(true));
await saveToken('id_token', token);
this.setState({loading: false}, () =>
this.props.navigation.navigate({
key: 'TabHome',
routeName: 'TabHome',
}),
);
})
.catch(error => {
console.log(error);
this.setState({loading: false, error: error.response.data});
});
};
render(){
...
<Text>{this.props.user.isLogin}</Text>
...
}
mapStateToProps = state => {
return {
isLogin: state.user,
};
};
export default connect(mapStateToProps)(Login);
似乎您正在使用以下内容映射redux状态:
mapStateToProps = state => {
return {
isLogin: state.user,
};
};
但是您正尝试通过以下方式访问isLogin
:
this.props.user.isLogin
看起来应该更改为:
this.props.isLogin.isLogin
但是]您可能希望将映射更改为以下内容:
mapStateToProps = state => { return { isLogin: state.user.isLogin, }; };
以便您可以简单地使用:
this.props.isLogin