我在使用React PureComponent和Immutable.js时遇到了一些问题。请考虑以下演示:
https://codepen.io/SandoCalrissian/pen/QaEmeX
其中有两个组件被呈现。第一个(NoramlPure)是一个普通PureComponent,第二个(ImmutablePure)是一个带有自定义shouldComponentUpdate的普通Component,它检查道具是否有equals方法。两者都以一个不可变的Map作为支柱,在每个渲染周期上都会进行重组。每次重新呈现时,它们都会向控制台打印一条消息。
然后触发两个呈现周期。
我希望两者都只呈现一次。然而,控制台显示了以下内容:
rendering
rendering normal pure component
rendering immutable pure component
rendering
rendering normal pure component我的自定义组件按预期工作,但是内置的PureComponent同时呈现两次(尽管获得了相同的数据)。
考虑到与Immutable.js PureComponent的链接(而且它们都是由Facebook创建的),我希望两者能够自然地合作,但据我所知,PureComponent从来没有调用过任何Immutable.js等式检查器。
有什么方法可以让PureComponent**s与对象一起工作吗?还是我被困在整个项目中使用** PureImmutable 组件作为基类?
发布于 2017-12-21 12:29:35
嗨,桑迪,问题是,在每次渲染中,你都在重新创建地图支柱,而React.PureComponent基本上是在检查props.map、===、nextProps.map。他们是不同的,所以它重新渲染。
检查一下这个:
class NormalPure extends React.PureComponent<any, any> {
public render() {
console.log("\trendering normal pure component");
return <div />;
}
}
class ImmutablePure extends React.Component<any, any> {
public shouldComponentUpdate(nextProps) {
return !Object.keys(this.props).every((key) => {
const val = this.props[key];
const nextVal = nextProps[key];
if (typeof val.equals === "function") {
return val.equals(nextVal);
} else {
return val === nextVal;
}
});
}
public render() {
console.log("\trendering immutable pure component");
return <div />;
}
}
const wrapper = document.getElementById("wrapper");
const obj = {
"a": 1,
"b": 2,
"c": 3,
};
const immutableMap = Immutable.fromJS(obj);
function render() {
console.log("rendering");
ReactDOM.render(
<div>
<NormalPure map={immutableMap} />
<ImmutablePure map={Immutable.fromJS(obj)} />
</div>,
wrapper
);
}
render();
render();有办法让PureComponents与Immutable.js对象一起工作吗?否。PureComponent使用严格的等式比较(===)。它不知道什么是永恒的
还是我被困在整个项目中使用PureImmutable组件作为基类?是的,如果您想用方法检查Immutablejs对象。
https://stackoverflow.com/questions/47924559
复制相似问题