我正在尝试使用React Redux(SSR和Thunks)实现auth(注册/注销).当Redux状态更新时,我不知道为什么组件没有更新… 这是应该重新呈现的组件: class Navbar extends React.Component { constructor(props) { supe
这是应该重新呈现的组件:
class Navbar extends React.Component {
constructor(props) {
super(props);
this.state = {
loggedIn: props.authentication.loggedIn
};
}
render() {
let links = null;
if (this.state.loggedIn) {
links = ...
} else {
links = ...
}
return (<Toolbar>{links}</Toolbar>)
}
}
const mapStateToProps = state => {
return {
authentication: state.authentication
}
}
const mapDispatchToProps = dispatch => {
return {
signOut: () => {dispatch(userActions.logout())}
}
}
const AuthNavbar = connect(mapStateToProps, mapDispatchToProps)(Navbar)
export default AuthNavbar;
这是我的减速机:
const reducers = {
authentication,
registration,
alert
}
const todoApp = combineReducers(reducers)
export default todoApp
身份验证减速器:
const authentication = (state = initialState, action) => {
switch (action.type) {
...
case userConstants.LOGIN_SUCCESS:
return Object.assign({}, state, {
loggedIn: true,
loggingIn: false,
user: action.user
});
...
default:
return state;
}
}
和行动 – 登录:
function login(email, password) {
return dispatch => {
dispatch({type: userConstants.LOGIN_REQUEST, email});
userService.login(email, password).then(
user => {
dispatch({type: userConstants.LOGIN_SUCCESS, user});
},
error => {
dispatch({ type: userConstants.LOGIN_FAILURE });
dispatch({type: alertActions.error(error)});
}
);
}
}
UserService.login是一个调用和获取api的函数.
看起来Action应该被触发,Redux状态会更新,但组件不会更新:
双重检查Redux Dev Tools – 状态确实已更新,因此我使用连接实用程序的方式一定存在问题?
当一个新的道具回来时,你没有更新状态.
要么直接使用道具:
if (this.props.authentication.loggedIn) {
links = ...
或者在componentWillReceiveProps更新状态
componentWillReceiveProps(nextProps){
// update the state with the new props
this.setState({
loggedIn: nextProps.authentication.loggedIn
});
}
