2017-11-11 30 views
3

我是新与反应母语和终极版,我想知道我怎样才能发出后更新状态后,得到国家更新中...如何调度

按照我的代码:

/LoginForm.js

function mapStateToProps(state) { return { user: state.userReducer }; } 

function mapDispatchToProps(dispatch) { 
    return { 
    login: (username, password) => {  
     dispatch(login(username, password)); // update state loggedIn 
    } 
    } 
} 

const LoginForm = connect(mapStateToProps, mapDispatchToProps)(Login); 
export default LoginForm; 

/Login.js ---在这里,我一个按钮,调用此方法loginOnPress()

loginOnPress() { 
    const { username, password } = this.state; 
    this.props.login(username, password); 
    console.log(this.props.user.loggedIn) 
    } 

根据上述我的代码,我称第一方法'this.props.login(用户名,密码);',它调用调度并更改状态'loggedIn'。

此后,我试图让状态更新,但没有成功:

console.log(this.props.user.loggedIn) 

注:当我点击第二次这个按钮状态变为更新

+0

您应该检查道具'componentWillReceiveProps'生命周期钩子的变化,因为当你在尝试设置它们后检查下一行的道具时,它们的变化可能还没有传播回你的组件。 – wostex

回答

1

函数this.props.login(username, password)在redux状态上分派登录操作。

启动store.getState()确实会立即让你更新后的终极版状态,但通常情况下,你并不真正需要做的,因为它包装你的组件终极版connect功能。

终极版connect功能与新道具更新您的组件,所以你通常会做的是“捕获”这些变化的react lifecycle以下功能之一:

class Greeting extends React.Component { 

    ... 

    loginOnPress() { 
    const { username, password } = this.state; 
    this.props.login(username, password); 
    } 

    // before the new props are applied 

    componentWillReceiveProps (nextProps) { 
    console.log(nextProps.user.loggedIn) 
    } 

    // just before the update 

    componentWillUpdate (nextProps, nextState) { 
    console.log(nextProps.user.loggedIn) 
    } 

    // immediately after the update 

    componentDidUpdate (prevProps, prevState) { 
    console.log(this.props.user.loggedIn) 
    } 

    render() { 
    ... 
    } 
} 
+0

这正是我所需要的,并感谢您的所有细节 –

1

呼叫调度会更新状态立即但您的组件稍后会更新,以便您可以使用componentWillReceiveProps对道具中的更改作出反应,您可以看看here,以更好地解释React中状态更改的工作方式

+0

这正是我需要的! 感谢您的帮助 –