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

时间:2018-09-28 08:51:21

标签: javascript reactjs redux react-redux

我试图在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教程进行操作。

有人可以帮我吗?

4 个答案:

答案 0 :(得分:3)

构造函数中的这一行

let switchLanguage = this.props.switchLanguage;

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

线索以Android Studio 3.2 Build #AI-181.5540.7.32.5014246, built on September 17, 2018 JRE: 1.8.0_152-release-1136-b06 x86_64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Mac OS X 10.11.6 为名。

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

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

因此,props,带有您需要的任何参数。

答案 3 :(得分:0)

在构造函数中,您有这个let switchLanguage = this.props.switchLanguage;,但是问题是您的this.props.switchLanguage不接受任何参数,并且当您尝试在componentDidMount中调用时,您试图传递参数{ {1}}当然不起作用。

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

componentDidMount()
相关问题