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

React数组State更新失败:Uncaught TypeError: Cannot read property 'Selected' of null

Fixing "Cannot read property 'Selected' of null" When Updating Array State in React

Let’s break down exactly why you’re hitting this error and how to fix it—there are two key issues in your code causing the problem:

1. Constructor Syntax Error

Your constructor has a critical mistake in how you initialize the component state. The super(props) call should be a standalone line, and the state assignment needs to live directly inside the constructor, not nested inside the super call’s block.

Wrong Constructor:

constructor(props){
  super(props){
    this.state = { Selected: [] }
  }
}

Corrected Constructor:

constructor(props){
  super(props); // Properly call super first
  this.state = { Selected: [] }; // Initialize state directly in the constructor
}

This error was preventing your component from setting up this.state correctly, leading to this.state being null when you tried to access this.state.Selected.

2. Unbound Event Handler

The clickevent method isn’t bound to your component instance, so when it runs, this refers to undefined (or null in strict mode). That means this.state doesn’t exist when you try to update it.

You have three solid ways to fix this:

Option 1: Bind the handler in the constructor

Add this line right after initializing your state:

this.clickevent = this.clickevent.bind(this);

Option 2: Use an arrow function for the handler

Arrow functions automatically bind this to the component instance, so no extra binding is needed:

clickevent = (newItem) => {
  this.setState({ Selected: [...this.state.Selected, newItem] });
}

Option 3: Wrap the handler in an arrow function when attaching it

When you add the click event to your UI element, wrap the call in an arrow function:

<button onClick={() => this.clickevent("new-item-value")}>Add Item</button>

Full Corrected Code Example

Here’s how your component should look with both fixes applied (using option 1 for binding):

export interface IState { Selected: any[] }

export class MyComp extends React.Component<{}, IState> {
  constructor(props) {
    super(props);
    this.state = { Selected: [] };
    this.clickevent = this.clickevent.bind(this); // Bind the handler
  }

  clickevent(newItem) {
    // Immutable update using spread operator (safe and clean)
    this.setState({ Selected: [...this.state.Selected, newItem] });
    
    // Alternatively, if you need to rely on previous state:
    // this.setState(prevState => ({
    //   Selected: [...prevState.Selected, newItem]
    // }));
  }

  render() {
    return (
      <div>
        <button onClick={() => this.clickevent("new item")}>Add to Selected</button>
        <ul>
          {this.state.Selected.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
      </div>
    );
  }
}

Quick Note on Immutable State

Your approaches using the spread operator, concat, or slice + push are all valid—they create a new array instead of mutating the existing state array. Stick with these patterns to avoid unexpected React behavior.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:04:55