从mapDispatchToProps调度后导航到新组件

时间:2018-01-11 19:45:26

标签: react-native redux

通过单击英语或法语按钮为我的应用程序设置语言后,我需要导航到下一个屏幕。如何在this.props.navigation.navigate('HomeScreen')之后直接致电dispatch

我尝试将两者放在一个函数中并从onPress调用它,但这不起作用。

LanguageScreen.js

<Button
 title="English"
 onPress={this.props.english}
 />
 <Button
 title="Français"
 onPress={this.props.french}
 />

LanguageContainer.js

import React, { Component } from 'react';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux';
import LanguageScreen from '../screens/LanguageScreen.js';

const mapStateToProps = (state, props) => ({
  language: state.language
})

const mapDispatchToProps = (dispatch) => ({
  french: () => {
    dispatch({ type: 'FRENCH' });
  },
  english: () => {
    dispatch({ type: 'ENGLISH' });
  },
})

export default connect(mapStateToProps, mapDispatchToProps)(LanguageScreen)

store.js

import { createStore } from 'redux'

export const language = (state = 'english', action) => {
  switch (action.type) {
  case 'FRENCH':
    return 'french';
  case 'ENGLISH':
    return 'english';
  default:
    return state;
  }
}

let store = createStore(language);

export default store;

1 个答案:

答案 0 :(得分:2)

mapDispatchToProps接受ownProps作为第二个参数,因此假设您的组件收到navigate道具,您可以尝试这样的事情:

const mapDispatchToProps = (dispatch, ownProps) => ({
  french: () => {
    dispatch({ type: 'FRENCH' });
    ownProps.navigation.navigate('HomeScreen');
  },
  english: () => {
    dispatch({ type: 'ENGLISH' });
    ownProps.navigation.navigate('HomeScreen');
  },
}