【问题标题】:Component don't re-render after redux modificationredux 修改后组件不会重新渲染
【发布时间】:2021-06-11 13:50:25
【问题描述】:

我在我的应用程序中使用 redux,起初,它可以按我的意愿工作。当我通过 reducer 在状态中添加一些东西时,我的组件会根据需要重新渲染。但是当我只修改状态内的属性值时,我的组件不会重新渲染。

如果您需要代码,我可以上传它(或某些部分),但我认为问题更多的是思维方式。

我的状态示例

state = {
    "BaliseSeen": {
        "Marseille": [
            {
                "id": "5566",
                "nom": "Notre dame de La Garde",
                "type": "Monument",
                "vue": true,
            },
        ],
        "Toulon": [
            {
                "id": "1122",
                "nom": "Isen Yncrea Méditerranée",
                "type": "Monument",
                "vue": true,
            },
            {
                "id": "3344",
                "nom": "Appartement n°69",
                "type": "Monument",
                "vue": true,
            },
            {
                "id": "6677",
                "nom": "Mairie",
                "type": "Info",
                "vue": false,
            },
        ],
    },
    "Medailles": [
        {
            "ville": "Toulon",
        },
    ],
    "User": [],

}

当我添加类似的新内容时,它会工作并重新渲染:

nextState = {...state,
      BaliseSeen: {
               ...state.BaliseSeen, [city]: [...state.BaliseSeen[city], { id: action.value.id, type: action.value.type, nom: action.value.nom, vue: action.value.vue }]
      }
}

但是当我只想将属性 vue 从 false 更改为 true 时,它可以工作(当我检查状态时应用了修改但我的组件没有重新渲染:

BaliseSeenIndex = state.BaliseSeen[city].findIndex(item => item.id === action.value.id)
nextState = state
nextState.BaliseSeen[city][BaliseSeenIndex].vue = true

(我也尝试从我的状态中删除元素并在之后添加它,但与之前一样,它可以在不渲染我的组件的情况下工作) 所以不知道怎么说状态被修改了

【问题讨论】:

  • 你能显示更多关于你修改状态的部分的代码吗?
  • Redux 状态不应该被改变。 nextState = {...state}应该可以解决你的问题redux.js.org/faq/immutable-datastackoverflow.com/a/48819216/5793132如果你真的想改变状态,你不应该使用redux,而是使用mobX mobx.js.org/the-gist-of-mobx.html
  • @UğurEren OP 也可以使用 immer 或 redux 工具包,或者只编写不会变异的代码。
  • 使用 immer 仍然会创建不可变对象。如果 op really 想要使用突变,我给了 mobx 选项作为替代方案,它的优点和缺点。但你也是正确的,通过使用 immer op 可以在他的 reducer 中编写可变代码,但结果仍然是不可变的

标签: javascript react-native redux react-redux redux-reducers


【解决方案1】:

如评论;您不应该变异,请改为执行以下操作

//not sure where cityp comes from but I assume it is from the action
return {
  ...state,
  BaliseSeen: {
    ...state.BaliseSeen,
    [city]: state.BaliseSeen[city].map((item) =>
      item.id !== action.value.id
        ? item//not the item we want to edit, return unchanged
        : {//item we are looking for, return changed copy
            ...item,
            vue: true,
          }
    ),
  },
};

【讨论】:

  • 非常感谢!我不知道该怎么做,你的回答很完美。再次感谢你:)
  • @Tomitom 不可变更新模式可以在here找到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2019-01-26
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-07-12
相关资源
最近更新 更多