Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs Typescript:对象在if in React之后可能是null事件_Reactjs_Typescript - Fatal编程技术网

Reactjs Typescript:对象在if in React之后可能是null事件

Reactjs Typescript:对象在if in React之后可能是null事件,reactjs,typescript,Reactjs,Typescript,我正在使用Typescript编写react应用程序,在渲染方法中出现以下错误: Object is possibly null 问题是我已经在检查对象是否为null。这是我的密码: interface State { tutorial: any; } export default class Tutorial extends PureComponent<any, State> { state = { tutorial: null, }; compone

我正在使用Typescript编写react应用程序,在渲染方法中出现以下错误:

Object is possibly null
问题是我已经在检查对象是否为null。这是我的密码:

interface State {
  tutorial: any;
}

export default class Tutorial extends PureComponent<any, State> {
  state = {
    tutorial: null,
  };

  componentDidMount() {
    loadTutorial(this.props.match.params.id).then((res: any) => {
      this.setState({ tutorial: res.tutorial });
    });
  }

  render() {
    if (this.state.tutorial === null) return null;

    return (
      <section>
        <h1>Tutorial: {this.state.tutorial.title}</h1>;
      </section>
    );
  }
}
接口状态{
教程:任何;
}
导出默认类教程扩展了PureComponent{
状态={
教程:空,
};
componentDidMount(){
loadTutorial(this.props.match.params.id)。然后((res:any)=>{
this.setState({tutorial:res.tutorial});
});
}
render(){
if(this.state.tutorial===null)返回null;
返回(
教程:{this.state.Tutorial.title};
);
}
}

但是我仍然有渲染方法中的错误。我如何解决它?

奇数错误。这似乎与这样一个事实有关:在初始化
状态
,并将
教程
设置为
时,没有类型注释:

state = {
  tutorial: null,
};
换句话说,TypeScript认为
state
的类型实际上是
{tutorial:null}
,因此不能缩小
null
的范围。然而,我希望它能缩小到
从不
,这就是我发现错误消息奇怪的原因

将其更改为:

state: Readonly<State> = {
  tutorial: null,
};
状态:只读={
教程:空,
};
和。(启用
stricnullchecks
进行验证。)


即使我发现要获得正确的行为,您通常必须显式地注释
state
属性,否则TypeScript将从初始化值推断类型,这可能与传递给组件的
S
类型参数不同。

是否使用严格的空检查?这是正确的答案。作为进一步的了解,问题是没有注释,状态被推断为
{tutorial:null}
。这意味着无论检查结果如何,
tutorial
始终为
null
。正确的错误应该是“无法访问的代码”,但我认为类型错误在这里具有优先权;如果(x.a!=null){x.a.hey;}谢谢!将state显式设置为Readonly或:state可解决此问题