为什么 react 异步接收 redux 状态的更新 [英] Why react receives updates for redux state asynchronously

查看:31
本文介绍了为什么 react 异步接收 redux 状态的更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

当我调度一个动作来改变我的 redux 状态时,React 组件异步接收改变的状态.但我想同步处理这些变化.

代码在这里:

//组件类 App 扩展了 React.Component {handleButtonChange = e =>{this.props.change("Hello World");console.log(this.props.title);//打印旧值setTimeout(() => {console.log(this.props.title);//打印新值}, 100);};使成为() {返回 (<div className="应用程序"><button onClick={this.handleButtonChange}>更改标题

);}}const mapStateToProps = state =>({标题:state.title});const mapDispatchToProps = dispatch =>({更改:标题 =>调度(更改(标题))});导出默认连接(mapStateToProps,mapDispatchToProps)(应用程序);

有什么想法吗?

完整示例在这里:

<小时>

因此,如果你想第一次使用新的计算道具,它被更新了,你应该在componentDidUpdate()

不过,我也看到你想在分派动作后直接使用新的props:

this.props.change("Hello World");//到此为止,创建一个新组件,合并 props,然后执行下一行console.log(this.props.title);

我认为这在某种程度上是不可能的.

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

I have a little problem in my React/Redux application.

When I dispatch an action to change my redux state, React component receives the changed state asynchronously. But I want to handle the changes synchronously.

The code is here:

// 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);

Any ideas?

The full example is here: https://codesandbox.io/s/lxjkvvk3pl

解决方案

The connect() method, it does not modify the component class passed to it; instead, it returns a new, connected component class for you to use.

The mapStateToProps() function is called any time the connector component needs to compute new props, as a result of a store state change.

Reference: react-redux api


When you dispatch an action:

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

Which will make the store state change, as a result, the mapStateToProps() function will be invoked and the connect() function will get the current component and return for you a new component with the updated props.

The console.log(this.props.title) is executed with the value of the property title of the old props object of the old component.


I put some lifecycle hooks in your codes to see what actually happened:

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);


And the results after clicking four times on the button are:


Therefore, in case you want to use the new computed props for the first time, it's updated, you should do it in the componentDidUpdate()

However, I also see that you want to use the new props directly after dispatching an action:

this.props.change("Hello World");
// stop here, creating a new component, merging props, then executing the next line
console.log(this.props.title); 

I think that's somehow impossible.

The rework demo: https://codesandbox.io/s/wol55qqx0k

这篇关于为什么 react 异步接收 redux 状态的更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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