【发布时间】:2019-10-03 18:05:41
【问题描述】:
在下面的例子中:
interface AppState {
text: string | null;
}
interface ChildProps {
text: string;
}
class App extends React.Component<{}, AppState> {
state = {
text: null
};
componentDidMount() {
setTimeout(() => {
this.setState({ text: "rendered!" });
}, 5000);
}
render() {
return this.state.text !== null ? (
<Child text={this.state.text} />
) : (
"loading..."
);
}
}
class Child extends React.Component<ChildProps> {
render() {
const { text } = this.props;
return <div>{text}</div>;
}
}
<Child text={this.state.text} />下出现错误:
类型 'null' 不可分配给类型 'string'.ts(2322)
这没有意义,因为在渲染之前有一个明确的空检查。
为什么从状态中提取text时,错误消失了?
render() {
const { text } = this.state;
return text !== null ? (
<Child text={text} />
) : (
"loading..."
);
}
启用错误的工作示例,替换代码以查看它已修复:
【问题讨论】:
标签: javascript reactjs typescript