reactjs – React Redux组件不会更新
发布时间:2020-12-15 16:21:27 所属栏目:百科 来源:网络整理
导读:我正在尝试使用React Redux(SSR和Thunks)实现auth(注册/注销).当Redux状态更新时,我不知道为什么组件没有更新… 这是应该重新呈现的组件: class Navbar extends React.Component { constructor(props) { super(props); this.state = { loggedIn: props.auth
我正在尝试使用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 身份验证减速器: 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的函数. 双重检查Redux Dev Tools – 状态确实已更新,因此我使用连接实用程序的方式一定存在问题? 解决方法
您将logedin props存储在构造函数内的状态中,该构造函数将在组件的生命周期中仅运行一次.
当一个新的道具回来时,你没有更新状态. 要么直接使用道具: if (this.props.authentication.loggedIn) { links = ... 或者在 componentWillReceiveProps(nextProps){ // update the state with the new props this.setState({ loggedIn: nextProps.authentication.loggedIn }); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |