父组件:
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
,但 one
、two
或 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/