从数组中删除项目(React-Native + Redux)

时间:2017-09-03 12:43:16

标签: javascript reactjs react-native redux

我有用户的清单,当我点击复选框时,用户应该添加到InputField或从InputField删除,如果我再次检查它。

目前仅适用于ADD。

import ...

export default class NewEvent extends React.Component {
  constructor(props) {
    super(props);
    this.onSelect = this.onSelect.bind(this);
  }

  onSelect = id => { 
    addMembers(id) }

  findSelectedContacts = (contacts, membersArray) => {
    const newArr = [];
    contacts.forEach(item => {
      if(membersArray.indexOf(item.id.toString()) > -1) {
        newArr.push(` ${item.name}`)
      }
    });
    return newArr;
  }

  render() {
    const { navigation, members, location, contacts } = this.props;
    const membersArray = members ? members.split(',') : [];
    const selectedArray = this.findSelectedContacts(contacts, membersArray)
    const inputFill = selectedArray.join().trim();
    return (

            <InputField
              customStyle={[eventStyles.input]}
              icon="addGuest"
              placeholder="Add guests"
              onGetText={texts => {
                this.handlerChangeText(texts)
              }}
              value={inputFill}
            />
    );
  }
}

另外,我有减速器,可以为客人添加输入:

import { handleActions } from 'redux-actions';
import * as types from '../actions/actionTypes';

export const initialState = {
  members: '',
};

const addMembers = (members, id) => {
  const res = members ? `${members},${id}` : `${id}`;
  return res;
}

export default handleActions(
  {
    [types.ADD_GUEST]: (state, action) => ({
      ...state,
      members: addMembers(state.members, action.payload),
    }),
  },
  initialState
);

请告知我如何更换减速机?如果我点击ONE复选框,我需要在InputFiled中添加或删除用户。

1 个答案:

答案 0 :(得分:1)

目前,您似乎将成员列表存储为以逗号分隔的字符串。更好的选择是将列表存储为实际数组,然后在该格式需要时将其转换为字符串,例如渲染。

它的reducer可能看起来像这样(试图遵循你现有的代码风格:

export const initialState = {
  // initialState changed to array
  members: [],
};

const addMember = (members, id) => {
  // add id to the end of the list
  return members.concat(id);
}

const removeMember = (members, id) => {
  // return a new list with all values, except the matched id
  return members.filter(memberId => memberId !== id);
}

export default handleActions(
  {
    [types.ADD_GUEST]: (state, action) => ({
      ...state,
      members: addMember(state.members, action.payload),
    }),

    [types.REMOVE_GUEST]: (state, action) => ({
      ...state,
      members: removeMember(state.members, action.payload),
    }),
  },
  initialState
);

如果您需要将列表作为字符串,在组件render()方法中 - 或者最好在您的react-redux mapStateToProps选择器中,您可以将其转换为字符串:

memberList = state.members.join(',')