2017-09-03 34 views
0

我有用戶的清單,當我點擊複選框時,用戶應該添加到InputField或從InputField刪除,如果我再次檢查它。從數組中刪除項目(React-Native + Redux)

現在只適用於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

目前,您似乎將成員列表存儲爲以逗號分隔的字符串。一個更好的選擇是將列表存儲爲實際數組,然後在需要時以該格式將其轉換爲字符串。渲染。

它可能是這個樣子(試圖按照現有的代碼風格的減速機:

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()方法 - 或preferrably在反應 - 終極版mapStateToProps選擇,你可以將其轉換爲字符串:

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

我的理解,我需要通過removeMember像道具的地方,不要我 –

+0

不完全是你確實需要派遣與動作。鍵入'types.REMOVE_G UEST'和'id'的負載,然後reducer會爲你調用'removeMember'方法。 – jevakallio

+0

我問,因爲我使用了你的代碼,它只添加成員但不刪除它。 –