简体   繁体   中英

react / redux - How to dispatch an action on componentDidMount

I'm trying to dispatch an action on my ComponentDidMount, but it never works.

The situation is: I've created a function to switch language on a reducer, who initialize the language to the browser language. And I want to change the language to the first language available on my API when I call my component.

I tried a lot of things from StackOverflow and I don't understand why when I put my function on the render (onClick, onScroll) it works fine, but on my componentDidMount, it doesn't.

Here's my code:

import {switchLanguage} from '../actions/langs'

class Header extends Component {
  constructor(props) {
    super(props);

    this.state = {
      langs: langs
    };

    let switchLanguage = this.props.switchLanguage;
  }

  componentDidMount() {
    switchLanguage(1, 'fr')
  }

  render() {
    [...]
  }
}

function mapStateToProps(state) {
  return {langId: state.languageReducer.id, language: state.languageReducer.language}
}

function mapDispatchToProps(dispatch) {
  return {
    switchLanguage: (id, lang) => dispatch(switchLanguage(id, lang))
  }
}

Header = connect(mapStateToProps, mapDispatchToProps)(Header);

export default injectIntl(Header);

I'm new on Redux, I just follow the redux tutorial to do this.

Can someone help me?

this line in your constructor

let switchLanguage = this.props.switchLanguage;

does nothing, because a variable declared with let "dies" at the end of the constructor() { } statement. You have to call it this way:

componentDidMount() {
   this.props.switchLanguage(1, 'fr')
}

我认为您应该在componentDidMount上调用this.props.switchLanguage(1, 'fr')

The clue is in the name mapDispatchToProps .

If you look into the definition of mapDispatchToProps , switchLanguage ( the key ) is a function that calls dispatch ( it dispatches something ).

Since you are mapping this ...ToProps , it only makes sense that you will find the function that calls dispatch in props .

Therefore, this.props.switchLanguage , with whatever arguments you need.

In your constructor you have this let switchLanguage = this.props.switchLanguage; but problem is your this.props.switchLanguage doesn't accept any parameters, and when you try to invoke in componentDidMount , you tried to pass in parameters switchLanguage(1, 'fr') which of course not working.

Instead, you can directly call the method in your componentDidMount() as below, and remove the declaration of method in your constructor

componentDidMount(){
  this.props.switchLanguage(1, 'fr');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM