【问题标题】:Can I block prerender children on React Fiber?我可以在 React Fiber 上阻止 prerender children 吗?
【发布时间】:2018-05-20 06:12:03
【问题描述】:

我在 React Fiber 上编写了组件。 该组件接收 1 个 cond 道具,这是真的,渲染孩子。

"use strict";
import * as React from "react";
import * as ReactDOM from "react-dom";

interface IfProps {
  cond: boolean;
}

export class If extends React.Component<IfProps, {}> {
  render() {
    const {cond, children} = this.props;

    if (cond) {
      return children;
    } else {
      return null;
    }
  }
}

class TopComponent extends React.Component {
  render() {
    let str: any = null;

    return (
      <div>
        <If cond={str != null}>
          This part not showed.
          {str.length}
        </If>
      </div>
    );
  }
}

ReactDOM.render(<TopComponent />, document.getElementById("app"));

在 React Fiber 之前,此代码有效。但是现在,React Fiber 会导致错误。

Uncaught TypeError: Cannot read property 'length' of null

我猜 React Fiber 在渲染组件之前渲染子组件。 但是这种行为会破坏组件。

我可以停止预渲染子组件吗?

【问题讨论】:

  • 你确定这以前有效吗?如果不先评估 str.length,就无法构造 &lt;If&gt; 的子代,而 Fiber 并没有改变这一点..
  • 对不起,我错了。我在 React 15 上尝试了代码,同样的错误导致...示例代码jsfiddle.net/kmdsbng/9gj83n6x/1

标签: javascript reactjs react-fiber


【解决方案1】:

您的问题不是 react 不接受 null 返回值。 (它的作用是ReactComponent.render) 但是您的孩子会在他们被移交给If 组件之前进行评估,这意味着str.length 会抛出您所看到的错误。

Basic example 基于您的代码。

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多