首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >具有反应纯成分的Immutable.js

具有反应纯成分的Immutable.js
EN

Stack Overflow用户
提问于 2017-12-21 12:00:46
回答 2查看 1.5K关注 0票数 3

我在使用React PureComponent和Immutable.js时遇到了一些问题。请考虑以下演示:

https://codepen.io/SandoCalrissian/pen/QaEmeX

其中有两个组件被呈现。第一个(NoramlPure)是一个普通PureComponent,第二个(ImmutablePure)是一个带有自定义shouldComponentUpdate的普通Component,它检查道具是否有equals方法。两者都以一个不可变的Map作为支柱,在每个渲染周期上都会进行重组。每次重新呈现时,它们都会向控制台打印一条消息。

然后触发两个呈现周期。

我希望两者都只呈现一次。然而,控制台显示了以下内容:

代码语言:javascript
运行
复制
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 组件作为基类?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-12-21 12:29:35

嗨,桑迪,问题是,在每次渲染中,你都在重新创建地图支柱,而React.PureComponent基本上是在检查props.map、===、nextProps.map。他们是不同的,所以它重新渲染。

检查一下这个:

代码语言:javascript
运行
复制
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对象。

票数 3
EN

Stack Overflow用户

发布于 2018-06-28 10:30:19

目前,您可以使用此ImmutablePureComponent实现而不是标准的PureComponent

https://www.npmjs.com/package/react-immutable-pure-component

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47924559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档