【发布时间】: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,就无法构造<If>的子代,而 Fiber 并没有改变这一点.. -
对不起,我错了。我在 React 15 上尝试了代码,同样的错误导致...示例代码jsfiddle.net/kmdsbng/9gj83n6x/1
标签: javascript reactjs react-fiber