如何在redux中更新特定数组项内的单个值 [英] How to update single value inside specific array item in redux

查看:48
本文介绍了如何在redux中更新特定数组项内的单个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,重新渲染状态会导致 ui 问题,并且建议仅更新我的减速器中的特定值以减少页面上的重新渲染量.

I have an issue where re-rendering of state causes ui issues and was suggested to only update specific value inside my reducer to reduce amount of re-rendering on a page.

这是我的状态的例子

{
 name: "some name",
 subtitle: "some subtitle",
 contents: [
   {title: "some title", text: "some text"},
   {title: "some other title", text: "some other text"}
 ]
}

我目前正在更新它

case 'SOME_ACTION':
   return { ...state, contents: action.payload }

其中 action.payload 是包含新值的整个数组.但现在我实际上只需要更新内容数组中第二项的文本,而这样的事情是行不通的

where action.payload is a whole array containing new values. But now I actually just need to update text of second item in contents array, and something like this doesn't work

case 'SOME_ACTION':
   return { ...state, contents[1].text: action.payload }

其中 action.payload 现在是我需要更新的文本.

where action.payload is now a text I need for update.

推荐答案

您可以使用 反应不变性助手

import update from 'react-addons-update';

// ...    

case 'SOME_ACTION':
  return update(state, { 
    contents: { 
      1: {
        text: {$set: action.payload}
      }
    }
  });

虽然我想你可能会做更多这样的事情?

Although I would imagine you'd probably be doing something more like this?

case 'SOME_ACTION':
  return update(state, { 
    contents: { 
      [action.id]: {
        text: {$set: action.payload}
      }
    }
  });

这篇关于如何在redux中更新特定数组项内的单个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆