score:4

Accepted answer

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:

enter image description here


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


Related Query

More Query from same tag