0

我在 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 在渲染组件之前渲染子组件。但是这种行为破坏了组件。

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

4

1 回答 1

0

您的问题不在于 react 不接受null返回值。(确实如此ReactComponent.render)但是您的孩子会在他们被移交给If组件之前得到评估,这意味着这str.length会引发您所看到的错误。

基于您的代码的基本示例。

于 2017-12-06T11:32:10.740 回答