我正在尝试使用React + Redux(SSR和Thunks)实现auth(注册/注销)。当Redux状态更新时,我不知道为什么组件没有更新......
这是应该重新呈现的组件:
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
身份验证reducer:
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 - 状态确实已更新,因此我使用连接实用程序的方式一定存在问题吗?
答案 0 :(得分:4)
您将logedin
道具存放在constructor
内的状态,该状态仅在组件的生命周期内运行一次。
当一个新的道具回来时,你没有更新状态。
直接使用道具:
if (this.props.authentication.loggedIn) {
links = ...
中的状态
componentWillReceiveProps(nextProps){
// update the state with the new props
this.setState({
loggedIn: nextProps.authentication.loggedIn
});
}
答案 1 :(得分:2)
您的render
功能取决于state.loggedIn
,但state.loggedIn
没有变化;只有this.props.authentication.loggedIn
正在响应该操作而发生变化。您的组件以其当前形式不需要状态。您可以删除它以使其工作:
class Navbar extends React.Component {
render() {
let links = null;
if (this.props.authentication.loggedIn) {
links = ...
} else {
links = ...
}
return (<Toolbar>{links}</Toolbar>)
}
}