派送后如何更新状态 [英] How to get state updated after dispatch

查看:38
本文介绍了派送后如何更新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 react-native 和 redux 的新手,我想知道如何在调度后更新状态...

I'm new with react-native and redux and I want to know how can I get the state updated after the dispatch...

关注我的代码:

/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(username, password);' 调用调度并更改状态 'loggedIn'.

According my code above, I call first the method 'this.props.login(username, password);' that calls the dispatch and change the state 'loggedIn'.

之后我尝试更新状态但没有成功:

And after that I try to get the state updated but without success:

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

注意:当我第二次点击这个按钮时,状态会更新

Note: When I click the second time on this button the state comes updated

推荐答案

this.props.login(username, password) 函数在 redux-state 上调度登录操作.

The function this.props.login(username, password) dispatches a login action on the redux-state.

启动 store.getState() 确实会在更新后立即为您提供 redux-state,但通常情况下,您实际上并不需要这样做,因为 redux connect 包装组件的函数.

Launching store.getState() will indeed immediately get you the redux-state after the update, but usually, you don't really need to do it because of the redux connect function that wraps your component.

redux connect 函数用新的 props 更新你的组件,所以你通常要做的是在 react 生命周期:

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() {
    ...
  }
}

这篇关于派送后如何更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆