我试图公开一个值,以便在组件之间共享:
我有这个减速器:
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做的第一个组件,所以我需要一些帮助来实现我需要的东西。
如果您想全局访问某个内容,则必须将其存储在应用程序状态(redux存储(中。在您的特定情况下,您希望存储e.selectedItem.id
。因此,除了设置状态之外(但是这是多余的,因为变量可以全局访问(。
你需要做什么?在onChange
函数中,您必须调度操作并传递参数。
onChange = (e) => this.props.dispatch(selectedServiceAction(e.selectedItem.id));
注意:要访问dispatch
功能,必须连接您的组件。
然后它将被减速器捕获并保存在商店中。