[英]How can I expose a value to the global actions to share it among components?
我試圖公開一個值,以便在組件之間共享它:
我有這個減速器:
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
功能,必須連接您的組件。
然后它將被減速器捕獲並保存在商店中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.