组件不会在状态更改时重新呈现 - Redux

时间:2018-05-02 01:12:25

标签: reactjs redux react-redux

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

组件(域)

...
<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并正确返回状态:

enter image description here

1 个答案:

答案 0 :(得分:0)

  

React Redux尝试通过浅平等来提高性能   引用检查shouldComponentUpdate中的传入道具,以及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);

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

或者,您可以浅层克隆受影响的孩子1。