为什么React异步接收Redux状态更新

时间:2018-10-12 11:36:19

标签: reactjs redux react-redux

我的React / Redux应用程序有一个小问题。

当我调度一个动作来更改我的redux状态时,React组件异步接收更改后的状态。但我想同步处理更改。

代码在这里:

// Component
class App extends React.Component {
  handleButtonChange = e => {
    this.props.change("Hello World");
    console.log(this.props.title);   // print old value
    setTimeout(() => {
      console.log(this.props.title); // print new value
    }, 100);
  };
  render() {
    return (
      <div className="App">
        <button onClick={this.handleButtonChange}>
          Change the title
        </button>
      </div>
    );
  }
}
const mapStateToProps = state => ({
  title: state.title
});
const mapDispatchToProps = dispatch => ({
  change: title => dispatch(change(title))
});
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

有什么想法吗?

完整的示例在这里:https://codesandbox.io/s/lxjkvvk3pl

1 个答案:

答案 0 :(得分:4)

connect()方法,它不会修改传递给它的组件类;而是返回一个新的,已连接的组件类供您使用。

由于存储状态更改,只要连接器组件需要计算新的道具,就会调用mapStateToProps()函数。

参考:react-redux api


调度动作时:

 this.props.change("Hello World");
 console.log(this.props.title); 

这将更改存储状态,结果,将调用mapStateToProps()函数,而connect()函数将获取当前组件,并为您返回具有更新后的{{ 1}}。

props使用 old 组件的 old 道具对象的属性值执行。


我在您的代码中添加了一些生命周期挂钩,以查看实际发生的情况:

console.log(this.props.title)

在按钮上单击四次次后的结果是:

enter image description here


因此,如果您是第一次使用新计算的道具,它会被更新,您应该在import React from "react"; import { connect } from "react-redux"; import { change } from "./actions"; class App extends React.Component { constructor(props) { super(props); console.log("contructor(): " + this.props.title); } handleButtonChange = e => { this.props.change("Hello World"); console.log("handleButtonChange(): " + this.props.title); }; componentDidMount() { console.log("componentDidMount(): " + this.props.title); } componentDidUpdate(prevProps) { // Typical usage (don't forget to compare props): if (this.props.title !== prevProps.title) { console.log("componentDidUpdate(): " + this.props.title); } } componentWillUnmount() { console.log("componentWillUnmount(): " + this.props.title); } render() { console.log("render(): " + this.props.title); return ( <div className="App"> <button onClick={this.handleButtonChange}>Change the title</button> </div> ); } } const mapStateToProps = state => ({ title: state.title }); const mapDispatchToProps = dispatch => ({ change: title => dispatch(change(title)) }); export default connect( mapStateToProps, mapDispatchToProps )(App);

中进行操作

但是,我还看到您希望在分派操作后立即使用新的componentDidUpdate()

props

我认为这是不可能的。

返工演示:https://codesandbox.io/s/wol55qqx0k

相关问题