如何向全局操作公开值以在组件之间共享?

时间:2018-12-03 22:21:42

标签: javascript reactjs ecmascript-6 redux react-redux

我试图公开一个值,以便在各个组件之间共享它:

我有这个减速器:

import createReducer from '../../../redux/createReducer';
import ActionTypes from '../constants/ActionTypes';

const initialState = {
  currentService: 'otherservices',
};

export const handlers = {
  [ActionTypes.SELECTED_SERVICE_ACTION](state, action) {
    return {
      ...state,
      currentService: action.payload,
    };
  },
};

export default createReducer(initialState, handlers);

此操作:

import ActionTypes from '../constants/ActionTypes';

export const selectedServiceAction = service => ({
  type: ActionTypes.SELECTED_SERVICE_ACTION,
  payload: service,
});

export default selectedServiceAction;

我有这个组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { translate } from 'react-i18next';
import { DropdownV2 } from 'carbon-components-react';
import PropTypes from 'prop-types';
import TableMultiSelectItems from './TableMultiSelectItems';
import { selectedServiceAction } from '../actions/cancellations';

class TableMultiselect extends Component {
  constructor(props) {
    super(props);
    this.state = {
      itemState: 'otherservices',
    };
  }

  onChange = e => this.setState({ itemState: e.selectedItem.id });

  render() {
    const { t } = this.props;
    // Array of dropdown's items
    const menuItems = TableMultiSelectItems(t);

    return (
      <div>
        <DropdownV2
          items={menuItems}
          onChange={this.onChange}
        />
      </div>
    );
  }
}

const wrappedComponent = connect(
  () => ({
    serviceSelected: this.state.itemState,
  }),
  dispatch => ({
    serviceSelectedHandler: serviceSelected => {
      dispatch(selectedServiceAction(serviceSelected));
    },
  }),
)(TableMultiselect);

TableMultiselect.propTypes = {
  t: PropTypes.func.isRequired,
  serviceSelectedHandler: PropTypes.func.isRequired,
};

export default translate()(wrappedComponent);

我需要从上面的组件中获取onChange函数(itemState: e.selectedItem.id });)返回的值并公开它,以便将其捕获到另一个组件中并执行以下操作:

//other imports
import the-Action-To-Get-The-OnChange-Value from "..."

const Cancellations = () => (
  <React.Fragment>
    {the-Action-To-Get-The-OnChange-Value.id === 'thisID' ?
      <SLRequests/> : <SLDevices/>
    }
  </React.Fragment>
);

这是我尝试与Redux一起使用的第一个组件,因此我需要一些帮助来实现所需的功能。

1 个答案:

答案 0 :(得分:0)

如果您希望全局访问某些内容,则必须将其存储在应用程序状态(redux存储)中。在特定情况下,您想存储e.selectedItem.id。因此,除了设置状态外(这是多余的,因为该变量可以全局访问)。

您需要做什么?在onChange函数内部,您必须调度操作并传递参数。

onChange = (e) => this.props.dispatch(selectedServiceAction(e.selectedItem.id));

注意:要访问dispatch功能,必须连接您的组件。

然后它将被减速器捕获并保存在商店中。