【问题标题】:react, state change but not re-render反应,状态改变但不重新渲染
【发布时间】:2019-11-19 07:52:07
【问题描述】:

有一个案例让我很困惑。

我有一个对象 redux 状态:{ show: true, creative: {name: 'a', tags: [t1, t2, t3] } }。该对象已通过“react-redux”的“连接”功能映射到道具。

当我更改属性“show”或“creative.name”时,它会触发重新渲染。但是如果我将 t0 附加到“creative.tags”,它不会运行重新渲染。

# reducer.js
# block code does not re-render ===========
state.creative.tags.push(t0)
return state
# end block code does not re-render =======

我必须通过分配一个新变量来解决问题。

# reducer.js
# block code does re-render ===========
let new_state = Object.assign({}, state);
new_state.creative.dsp_tags.push(action.payload);
return new_state
# end block code does re-render =======

能否请您告诉我 reactJS 如何识别更改的状态?

【问题讨论】:

  • Reducer 永远不应该改变状态,而是返回一个新的状态对象,所以你正在做的作为你的解决方法是正确的。请参阅此处了解更多信息:redux.js.org/recipes/structuring-reducers/…
  • 谢谢,@djskinner。答案对我很有帮助

标签: reactjs react-redux


【解决方案1】:

您不能直接改变状态,您应该始终创建副本并返回新状态。 您直接推入标签的事实是导致问题的原因。

在返回状态对象之前创建一个新数组:

const newtags = [...state.creative.tags, action.payload];
let creative= Object.assign({}, state.creative, { tags: newtags } );
let new_state = Object.assign({}, state, { creative } );

【讨论】:

    【解决方案2】:

    Reducer 根据定义必须由 Pure Functions 的一个或集合组成。这意味着state 必须保留immutable。您可以使用像...state 这样的扩展操作来复制您的state 对象,然后进行必要的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-04
      • 2018-12-31
      • 2018-12-31
      • 2018-02-27
      • 2017-03-24
      • 2019-04-03
      • 1970-01-01
      • 2017-03-25
      相关资源
      最近更新 更多