2017-10-18 88 views
0

基本上我有一個訪問級別列表。我把它們放在每個列表項的列表和右側,我有一個開關。我試圖實現的是讓onPress事件來更新我的狀態,其中鍵已被按下的列表項。React交換機上的本機更新多維狀態值按

列表數據部分。我無法控制關鍵名稱。對於那個很抱歉。

accessList: 
Array(51) 
0: 
{FormID: 101, FormName: "ApplicationSettingCheckStoreID", FormDesc: "Activate Device", IsShow: true, Note: "ApplicationSettingCheckStoreID"} 
1: 
{FormID: 145, FormName: "GiftCardAddFundList", FormDesc: "Add Fund", IsShow: true, Note: "Add Fund"} 

的方式我使其

<List> 
    { 
     this.state.accessList.map((v, k) => { 
      return (
       <ListItem key={v.FormID}> 
        <Row> 
        <Col size={80}> 
         <Text>{v.FormDesc}</Text> 
        </Col> 
        <Col size={20}> 
         <Switch 
          value={v.IsShow} 
          onValueChange={() => this._switchToggled(v)} /> 
         </Col> 
        </Row> 
       </ListItem> 
      ); 
     }) 
    } 
    </List> 

這是我想正確填寫的一部分,但我已經失敗了多次。

_switchToggled = (listItem) => { 
     ... 
    } 

我真的很感謝任何幫助。謝謝。

回答

1

你在用什麼進行州管理,即你的accessList集合是如何存儲的?如果它是從redux來了,你可以通過一個動作與項目的索引要更新,像這樣:

_switchToggled = (listItem, index) => { 

    this.props.dispatch(actions.updateToggle({ index, IsShow: !listItem.isShow }); 
} 

actions.js文件看起來是這樣的:

const updateToggle = (payload) => { 
    return { 
    type: "UPDATE_TOGGLE", 
    payload 
    }; 
}; 

reducer會看起來是這樣的:

const reducer = (state, action) => { 
    case "UPDATE_TOGGLE": 

    // create a copy of the data 
    let clone = state.accessList.slice(); 

    // mutate the single item 
    let item = clone[action.payload.index]; 

    let newItem = { 
     ...item, 
     IsShow: action.payload.isShow 
    }; 

    // splice it into the clone 
    let newAccessList = clone.splice(action.payload.index, 1, newItem); 

    return { 
     ...state, 
     accessList: clone 
    }; 

    default: 
    return state; 
}; 

所以在你的reducer中,你實際上是複製你的數據結構來操作。這保留了Redux不應該直接改變state的原則,而是返回state的新表示。有權訪問您的accessList數組的索引是有幫助的,並且允許您執行splice並返回其狀態爲isShow狀態的項目。讓我知道如果我能用這個例子來幫助你。

+0

謝謝你花時間提供一個很好的解釋。我很欣賞這一點。它現在可以工作,謝謝你。 – ODelibalta

+1

真棒,真的很高興聽到它的工作!祝你好運! –