Redux:共享动作

时间:2016-12-19 09:54:16

标签: redux react-redux

我的应用程序中有一些操作需要由几个不同的反应组件共享。例如,我有一个fetchAPIData动作创建者,它接受一些参数并触发动作以进行提取(使用我自己编写的自定义提取中间件):

export function fetchAPIData(params) {

  const actions =  
    [
      types.API_CALL, 
      types.RECEIVE_API_DATA,
      types.API_ERROR
    ];

  const params = { 
    method: 'params.method',
    params
  };

  return fetch(actions, params);
};

此操作和其他此类操作需要通过应用的各个不同部分调用,因此我创建了一个common-actions目录,其中存在这些操作。这感觉就像错误的方法,所以我想知道是否有更可接受的方式这样做?

1 个答案:

答案 0 :(得分:0)

我建议您使用connect函数react-redux

然后,您可以将操作导入顶级组件,并将其与所需的状态绑定。然后把道具传给你想要的任何孩子。快速示例:

import React, { Component } from 'react';
// Import actions below
import * as myActions from '/redux/actions/myActions';
// Make sure redux, react-redux are installed
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

class App extends Component {
  render() {
    const { redux, actions } = this.props; // the redux state.
    const { actionName } = actions;
    <div>
      <button onClick={() => actionName()}> {/* Dispatching redux action... */}
        Dispatch action
      </button>
      <ChildComponent {...this.props} />, {/* Now you can pass the props to any children */}
    </div>;
  }
}

// take any state from redux you want and return it within redux object
const mapStateToProps = state => ({
  redux: {
    myState: state.myState,
  },
});

const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators({
    ...myActions,
    // import actions below...
  }, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App); // The component name you want to bind the state and the actions to.

我留下了笔记,这样你才能理解发生了什么。这是ES6。