【问题标题】:How to update single value inside specific json array item using redux (Flatlist item click)?如何使用 redux(Flatlist 项目单击)更新特定 json 数组项目中的单个值?
【发布时间】:2017-12-05 10:08:47
【问题描述】:

我有一个显示名称和状态的平面列表, 我想通过单击平面列表项单击来切换用户的状态。 为此,我创建了 redux action 和 redux reducer。但无法更改当前状态。

itemClick (item,index) {
  const value=false;
  this.props.listItemClick({props:'status',value});
  }


 export default (state = INITIAL_STATE, action) => {
     switch (action.type) {
        case LIST_CLICK:
        console.log(action.payload.props);
            return {...state,[action.payload.props]: action.payload.value};
        default:
            return state;

    }
};

但无法更改指定用户对应的状态。例如 Raj 状态为 false

{
"response": [{
  "name": "RAJ",
   "status": true

 }, {
 "name": "RAM",
  "status": true,

}]
}


  <FlatList
     showsVerticalScrollIndicator={false}
     removeClippedSubviews={false}
     data={this.props.response}
     ItemSeparatorComponent = {this.flatListItemSeparator}
     ListFooterComponent={this.flatListItemSeparator}
     keyExtractor={(item, index) => index}
     renderItem={({item,index}) => this.renderFlatListItem(item,index)}/>

【问题讨论】:

  • 可以在返回前合并数据
  • 我是 redux 的新手。让我知道该怎么做
  • 你可以在console.log(action.payload.props);之前修改你的对象;
  • 但相同的 json 结果无法将状态更改为 false
  • 使用 Object.assign([],yourData)

标签: react-native redux react-redux


【解决方案1】:

我不知道这是否正是您想要实现的目标,但我会试一试。

//call Action 
this.props.listItemClick('RAJ',false});

//Action
export const listItemClick = (user,status) => {
    return {
        type: LIST_CLICK,
        payload: { user, status }
    };
}; 

 export default (state = INITIAL_STATE, action) => {
     switch (action.type) {
        case LIST_CLICK:
            //replace YOUR_DATA with your state var 
            return {...state, YOUR_DATA: [state.YOUR_DATA.map((val,index) => {
                   if (val.name === action.payload.user) {
                      return { ...val, status: action.payload.status };
                   }
                   return { ...val };
            })]};
        default:
            return state;

    }
};

【讨论】:

  • 我改变了 return {...val};及其工作正常。我在更改值后面临的唯一问题是 TypeError: Cannot read property 'replace' of undefined.
  • @praj 这是另一个问题,与我的实现无关;)可能您需要在另一个问题中提出这个问题。编辑:您的平面列表代码看起来不错
  • 我发现了问题:在调用 redux Array [ Object { "name": "RAJ", "status": true, }, Object { "name": "RAM", "status": true, } ] after Array [ Array [ Object { "name": "RAJ", "status": true, }, Object { "name": "RAM", "status": true, } ] ] ..top 数组是多余的
  • 我认为你必须删除我的评论'//用你的状态变量替换 YOUR_DATA'
  • return {...state, response: [state.response.map((val,index) => {
猜你喜欢
  • 2016-06-08
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多