javascript - React ImmutableJS - ShouldComponentUpdate

标签 javascript reactjs immutable.js

父组件:

import React, { Component } from 'react';
import { Child } from './Child';

const testObject = {
  test: {
    one: false,
    two: false,
    three: false,
  },
};

export class Parent extends Component {
  constructor() {
    super();
    this.state = {
      test: testObject.test,
    };
  }

  render() {
    return (
      <Child test={ this.state.test } />
    )
}

子组件:

import React, { Component, PropTypes } from 'react';

export class Child extends Component {
  shouldComponentUpdate(nextProps) {
    return nextProps.test !== this.props.test;
  }

  render() {
    console.log('hey! i\'m rendering!!');
    return (
       <div>Child</div>
    );
  }
}

Child.propTypes = {
  test: PropTypes.object.isRequired,
};

问题: 现在,它不起作用。当假设 test.one 变为 true 时,shouldComponentUpdate 仍然会重新渲染。我阅读了 immutablejs 和 React doc 上的文档,但我仍然不明白。这对你们来说应该很容易,有人可以帮忙吗?

最佳答案

testObject 不是不可变的。当然它不能被另一个对象替换:禁止 testObject = anotherTestObject,但 onetwo Three 可以修改:testObject.one = true就可以了。 ImmutableJS 提供了禁止 testObject 值修改的机制。

调用 SetState 将创建一个新的 this.state.test,因此 nextProps.test !== this.props.test 始终返回 true。

关于javascript - React ImmutableJS - ShouldComponentUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37853432/

相关文章:

javascript - 不可变 JS - 在嵌套映射中获取值

javascript - RCharts - 按类别柱形图选择颜色

javascript - 如何访问 polymer 网络组件中的输入元素

javascript - 在 Dropzonejs 中调用 .processQueue() 时出错

javascript - 从 fancybox 中删除内联样式

javascript - React Native Expo 音频播放器错误 - 播放器不存在

javascript - 属性的单元测试失败,只能在单个节点上运行?

javascript - 使用没有 async/await 的 Promise 时, Electron 打开对话框会挂起

javascript - Immutable.js 记录上的方法会复制吗?

javascript - 使用 javascript 原型(prototype)系统创建共享结构的不可变对象(immutable对象)是否有意义