You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件渲染时出现Cannot read properties of null (reading 'articles')错误

错误原因与修复方案

问题根源

你遇到的Uncaught TypeError: Cannot read properties of null (reading 'articles')错误,核心原因是在类组件的构造函数中错误地将this.setState赋值为对象,而非正确初始化this.state。React类组件里,setState是用于更新状态的内置方法,不能直接赋值,这会导致this.state始终为null,渲染时读取this.state.articles自然触发报错。

修复步骤

将构造函数里的错误赋值改为直接初始化this.state:

错误代码片段

constructor() {
  super();
  console.log("This is a constructor.");
  this.setState = {
    articles: this.articles,
    loading: false,
  };
}

修复后的代码

constructor() {
  super();
  console.log("This is a constructor.");
  this.state = {
    articles: this.articles,
    loading: false,
  };
}

额外优化建议

  • 可以将类属性articles直接合并到this.state中,省去单独声明的步骤,简化代码结构:
export class News extends Component {
  constructor() {
    super();
    console.log("This is a constructor.");
    this.state = {
      articles: [
        {
          source: { id: "news24", name: "News24" },
          author: "AFP",
          title: "SA great hails 'mind-blowing' England as Proteas eye mammoth test",
          description: 'South Africa great Mike Procter hopes England\'s "mind-blowing" approach to Test cricket under captain Ben Stokes and coach Brendon McCullum is a sign of things to come.',
          url: "https://www.news24.com/sport/Cricket/Proteas/sa-great-hails-mind-blowing-england-as-proteas-eye-mammoth-test-20220815",
          urlToImage: "https://cdn.24.co.za/files/Cms/General/d/2280/908ffc719a2d42ed86d2df3c5007d908.jpg",
          publishedAt: "2022-08-15T07:20:45+00:00",
          content: 'South Africa great Mike Procter hopes England\'s "mind-blowing" approach to Test cricket under captain Ben Stokes and coach Brendon McCullum is a sign of things to come as they prepare to face his nat… [+2822 chars]',
        },
        // 其他文章对象依次放入
      ],
      loading: false,
    };
  }

  render() {
    // ...原有渲染逻辑
  }
}
  • 渲染时可选添加可选链操作符,避免后续状态更新时articles为null/undefined引发的报错:
{this.state.articles?.map((element) => {
  return (
    <div className="col-md-4" key={element.url}>
      <NewsItem
        title={element.title}
        description={element.description}
        imageUrl={element.urlToImage}
      />
    </div>
  );
})}

内容的提问来源于stack exchange,提问作者Hrishabh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:54:21