阵营与同一容器/ Redux的多个组件
我在这个技术栈很新的,但我感到困惑的事:阵营与同一容器/ Redux的多个组件
我有处理应该显示什么,以便用户在应用一个反应容器:
const mapStateToProps = (state) => {
return {
currentScreen: state.currentScreen
}
}
并且还处理时,应用程序应该改变当前画面:
const mapDispatchToProps = (dispatch) => {
return {
changeScreen: (newScreen) => {
dispatch(changeScreen(newScreen))
}
}
}
但 “连接” connect()仅与App组分:
import App from '../components/App'
const AppScreen = connect(
mapStateToProps,
mapDispatchToProps
)(App)
如何与所有组件共享changeScreen
函数?
当您定义mapDispatchToProps时,您将返回一个对象,然后映射到App的道具。因此,在您的App组件中,只需检查道具并注意您的功能changeScreen存在。这假设你已经定义了你正在做的引用。
你可以阅读更多关于连接功能如何在这里工作:https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options
您可以通过子组件的连接changeScreen
功能在他们的道具,或者你可以在其中使用mapDispatchToProps为好。
例如,如果App
有List
子组件:
<List changeScreen={this.props.changeScreen} />
创建一个新的文件actions.js,所以这个动作可以在任何地方调用。 例如:
export function changeScreen(newScreen){
return({
your code here....
});
}
你,现在APP组件(或者你可以从任何其他组件共享)
import { changeScreen } from './actions';
import { bindActionCreators } from 'redux';
,并使用调度bindActionCreators
function mapDispatchToProps(dispatch){
return bindActionCreators({ changeScreen }, dispatch);
}
希望这可以帮助!
您可以使用context
或dependency injection
使您的changeScreen function
全球。以下示例使用context
。
class App extends React.Component {
getChildContext(){
// assume you use <Provider> component from react-redux
const {dispatch} = this.context.store;
const {currentScreen} = this.props; // assume you pass state to props if not
// use this.context.store.getState().currentScreen instead.
return {
changeScreen: (newScreen) => {
dispatch(changeScreen(currentScreen));
}
}
}
....
}
App.childContextTypes = { store : React.PropTypes.object }
// in child component
class Child extends React.Component {
// call this.context.changeScreen anywhere inside your child component
someMehod(argument){
this.context.changeScreen(argument);
}
}
Child.contextTypes = { store : React.PropTypes.object }
如果发现添加contextTypes
到每个子组件时,它需要changeScreen
功能。你可以使用dependency injection
模式。这里是doc
你为什么不只是重新使用的connect
输出与多个组件,例如:
服务/ ChangeScreen。JS
// I'm using `Services` to differentiate from
// `Containers` which couples and exports components
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
...
function mapStateToProps(state) {
return {
currentScreen: state.currentScreen
}
}
function mapDispatchToProps(dispatch) {
return {
changeScreen: (newScreen) => {
dispatch(changeScreen(newScreen))
}
};
}
export default connect(mapStateToProps, mapDispatchToProps);
集装箱/ Home.js
import ChangeScreen from './../Services/ChangeScreen';
import Home from './../Components/Home';
export default ChangeScreen(Home);
集装箱/ Modal.js
import ChangeScreen from './../Services/ChangeScreen';
import Modal from './../Components/Modal';
export default ChangeScreen(Modal);
的changeScreen功能在应用程序组件successfuly定义,我想什么要知道如何在所有组件之间共享此功能,而无需在不同的容器中编写相同的代码s的每个组件 –