【问题标题】:How to get state updated after dispatch调度后如何更新状态
【发布时间】:2017-11-11 06:59:56
【问题描述】:

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

按照我的代码:

/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 '。

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

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

注意:当我第二次单击此按钮时,状态会更新

【问题讨论】:

  • 你应该检查 componentWillReceiveProps 生命周期钩子中的 props 更改,因为当你在尝试设置它们后检查下一行的 props 时,它们的更改可能还没有传播回你的组件。跨度>

标签: react-native redux react-redux


【解决方案1】:

调用 dispatch 将立即更新状态,但您的组件将稍后更新,因此您可以使用 componentWillReceiveProps 对道具的更改做出反应,您可以查看 here 以更好地解释状态如何改变在 React 中起作用

【讨论】:

  • 这正是我需要的!感谢您的帮助
【解决方案2】:

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

启动 store.getState() 确实会在更新后立即为您提供 redux 状态,但通常您并不需要这样做,因为包装了您的 redux connect 函数组件。

redux connect 函数会使用新的 props 更新您的组件,因此您通常会在 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() {
    ...
  }
}

【讨论】:

  • 这正是我所需要的,感谢您提供所有详细信息
猜你喜欢
  • 2019-12-04
  • 2019-11-15
  • 2019-05-31
  • 2019-11-02
  • 1970-01-01
  • 2021-08-29
  • 2021-05-31
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多