我正在使用新的react-navigation库来构建我的React Native应用程序。我将导航组件中的ActionCreators
传递给场景时遇到了问题。
我有AppContainer
包装整个应用程序。
import React, { Component } from 'react';
import { DrawerNavigator, addNavigationHelpers } from 'react-navigation';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { ActionCreators } from '../actions';
import DashboardContainer from './DashboardContainer';
import CustomersContainer from './CustomersContainer';
const ApplicationNavigation = DrawerNavigator({
Dashboard: { screen: DashboardContainer },
Customers: { screen: CustomersContainer },
});
class AppContainer extends Component {
render() {
return (
<ApplicationNavigation />
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(ActionCreators, dispatch);
}
export default connect(() => { return {} }, mapDispatchToProps)(AppContainer);
以下是CustomerContainer:
import React, {Component} from 'react';
import {View, Text, Button} from 'react-native';
export default class CustomerContainer extends Component {
btnPressed() {
this.props.listCustomers()
}
render () {
return (
<View style={{marginTop: 40}}><Text>Customer</Text>
<Button onPress={() => this.btnPressed()} title="Press Me!" />
</View>
);
}
}
现在我试图在我的CustomerContainer
this.props.listCustomers()
内拨打电话。问题是ActionCreator道具没有传递给屏幕。我已尝试将screenProps
道具添加到ApplicationNavigation
组件:
但出于某些原因,当我这样做时,我的应用程序不显示任何屏幕,它只是空白而没有错误。
更新
所以我更新了我的CustomerContainer
文件:
import React, {Component} from 'react';
import {View, Text, Button} from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { ActionCreators } from '../actions';
class CustomerContainer extends Component {
btnPressed() {
console.log(this.props.listCompanyCustomers())
}
render () {
return (
<View style={{marginTop: 40}}><Text>Customer</Text>
<Button onPress={() => this.btnPressed()} title="Press Me!" />
</View>
);
}
}
function mapStateToProps(state) {
return {
companyCustomers: state.companyCustomers
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(ActionCreators, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(CustomerContainer);
这现在有效;然而,这感觉就像是不正确的方式。
答案 0 :(得分:0)
redux connect基本上做的是:
因此,如果你连接AppContainer,它的孩子们就不会获得这些调度方法,除非AppContainer将它们传递给它的子节点(但这就是连接来防止它)。
总而言之,你应该连接任何需要使用派遣的组件,否则它不会得到它。
如果你不想复制粘贴mapDispatchToProps,你可以删除它并使用this.props.dispatch代替:
import { ActionCreators } from '../actions';
class CustomerContainer extends Component {
btnPressed() {
this.props.dispatch(ActionCreators.listCompanyCustomers());
}
render () {
return (
<View style={{marginTop: 40}}><Text>Customer</Text>
<Button onPress={() => this.btnPressed()} title="Press Me!" />
</View>
);
}
}