【问题标题】:Component not re-rendering on state change - Redux组件不会在状态更改时重新渲染 - Redux
【发布时间】:2018-05-02 01:12:24
【问题描述】:

我无法让我的组件在状态更改时重新渲染。我相当有信心我不会改变状态。

组件(域)

...
<Add
   onClick={() => {
   domain.routes.push({
     from: 'foo',
     to: 'bar'
   });
   this.props.setDomain(this.props.domainIndex, domain);
}} />
...

减速器

case 'SET_DOMAIN':
  let tmpState = {...state}
  tmpState.domains[action.index] = action.value;
  return {...tmpState}

动作

export const setDomain = (index, domain) => ({
  type: 'SET_DOMAIN',
  value: domain,
  index: index
});

容器

import { connect } from 'react-redux';
import { setDomain, setRoute } from '../actions';
import Domain from '../components/pages/domain';

const mapStateToProps = state => ({
  domains: state.domains
});

const mapDispatchToProps = dispatch => ({
  setDomain: (index, domain) => dispatch(setDomain(index, domain)),
  setRoute: (domainIndex, routeIndex, route) =>
    dispatch(setRoute(domainIndex, routeIndex, route))
});

export default connect(mapStateToProps, mapDispatchToProps)(Domain);

从 redux chrome 扩展我可以看到 setDomain 正在被调用并且状态正在正确返回:

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    React Redux 尝试通过浅相等来提高性能 对 shouldComponentUpdate 中传入 props 的引用检查,以及 if 所有引用都相同, shouldComponentUpdate 返回 false 到 跳过实际更新您的原始组件。

    请务必记住,每当您更新嵌套值时, 您还必须返回您所在州的任何上述内容的新副本 树。如果你有 state.a.b.c.d,并且你想更新 d, 您还需要返回 c、b、a 和 state 的新副本。

    来自https://redux.js.org/faq/react-redux#react-not-rerendering

    {...object} 只是一个浅克隆。对象的子对象仍将具有相同的引用。因此,对于 Redux,子对象不会更新。

    我认为解决这个问题的最快方法是使用 Lodash cloneDeep

    let tmpState = _.cloneDeep(state);
    

    tmpState.domains = _.cloneDeep(tmpState.domains);
    

    但这确实会带来性能成本。

    或者,您可以一个一个地浅克隆受影响的孩子。

    【讨论】:

      猜你喜欢
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多