简体   繁体   中英

How can I grab values to share with some other components from an array of checkboxes using Redux?

I have this array:

const CheckboxItems = () => [
  {
    value: 'itemsCancelled',
    id: 'checkBoxItemsCancelled',
    labelText: 'Items Cancelled',
  },
  {
    value: 'requestDate',
    id: 'checkboxRequestDate',
    labelText: 'Request Date',
  },
];

export default CheckboxItems;

Which I need to set the values to another component depending on if the checkboxes are checked or not.

By default the checkboxes are going to be checked.

This is the component I am using:

       {CheckboxItems().map(item => (
          <ToolbarOption key={item.id}>
            <Checkbox
              defaultChecked
              id={item.id}
              labelText={item.labelText}
              value={item.value}
              onChange={onChange}
              columnsFilterHandler={columnsFilter}
            />
          </ToolbarOption>
        ))}

Here the dispatcher on that same component:

connect(
    ({ cancellations }) => ({
      columnsSelected: cancellations.columnsSelected,
    }),
    dispatch => ({
      columnsFilterHandler: columns => {
        dispatch(columnsFilter(columns));
      },
    }),
  ),

This is the action:

const columnsFilter = columns => ({
  type: ActionTypes.COLUMNS_FILTER,
  payload: columns,
});

And the reducer:

[ActionTypes.COLUMNS_FILTER](state, action) {
    return {
      ...state,
      columnsSelected: action.payload,
    };
  },

But I need to handle the state of those checkboxes separately, what can I do?

First of all I recommend you to use the newest sintax used in redux, and using mapStateToProps and mapDispatchToProps just to everybody can understand and help you better.

I think that if you are going to share these two checkboxes around your app, you just have to store in redux the id and the value (checked or not). The minimun necessary state.

In the initialState you can init with checkboxes:[{ checked: true, id: 'checkBoxItemsCancelled' }, { checked:true, id: 'checkboxRequestDate' }]

The action could be something like changeChecked receiving an id, like:

const changeChecked = id => ({ type: CHANGE_CHECKED_CHECKBOX, payload: {id}, });

And the reducer something like: case CHANGE_CHECKED_CHECKBOX: return state.checkboxes.map(checkbox => { if (!checkbox.id === action.payload.id){ return checkbox } return {...checkbox, checked: !checkbox.checked} })

Finally you can access these values in mapStateToProps and in the onChange function in the checkbox you launch the action changeChecked with the id.

I hope to help you, if you need something just reply :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM