繁体   English   中英

react / redux-如何在componentDidMount上调度动作

[英]react / redux - How to dispatch an action on componentDidMount

我试图在ComponentDidMount上调度一个动作,但是它永远无法正常工作。

情况是:我创建了一个函数来在化简器上切换语言,该化简器将语言初始化为浏览器语言。 我想在调用组件时将语言更改为API上可用的第一语言。

我从StackOverflow尝试了很多东西,但我不明白为什么将函数放在呈现器上(onClick,onScroll)可以正常工作,但是在我的componentDidMount上却不能。

这是我的代码:

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

我是Redux的新手,我只是按照redux教程进行操作。

有人能帮我吗?

您的构造函数中的这一行

let switchLanguage = this.props.switchLanguage;

什么也不做,因为在constructor() { }语句的末尾用let “ dies”声明的变量。 您必须这样称呼:

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

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

提示位于名称mapDispatchToProps

如果查看mapDispatchToProps的定义,则switchLanguage (键)是一个调用dispatch(它分发某些东西)的函数。

由于您正在映射this ...ToProps ,因此只有在props找到调用dispatch的函数才有意义。

因此, this.props.switchLanguage带有所需的任何参数。

在您的构造函数中,您需要let switchLanguage = this.props.switchLanguage; 但是问题是您的this.props.switchLanguage不接受任何参数,并且当您尝试在componentDidMount调用时,您尝试传递的参数switchLanguage(1, 'fr')当然不起作用。

相反,您可以按如下所示直接在componentDidMount()调用方法,并在构造函数中删除方法的声明

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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