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

在JSX中展示状态列表:React点击按钮添加字母后视图未更新?

解决React状态数组更新不触发渲染的问题

Hey there! I see the issue with your code—let's fix it up.

The problem is that you're directly mutating the existing state array with letters.push("d"). React relies on immutability to detect state changes: if you modify the original array (which still holds the same memory reference), React won't recognize that the state has changed, so it won't re-render your component to show the new letter.

Here's how to fix it:

You need to create a new array instead of modifying the existing one. There are a few clean, React-friendly ways to do this:

  • Use the spread operator (most concise and popular)
    Make a copy of the existing array, add your new item to it, then update state with this fresh array:

    addLetter = () => {
      this.setState({ 
        letters: [...this.state.letters, "d"] 
      });
    };
    
  • Use Array.concat()
    The concat method returns a brand new array with your added item, leaving the original state array completely untouched:

    addLetter = () => {
      this.setState({ 
        letters: this.state.letters.concat("d") 
      });
    };
    

Full modified code:

class App extends React.Component {
  state = { letters: ["a", "b", "c"] };

  addLetter = () => {
    // Create a new array instead of mutating the original state
    this.setState({ letters: [...this.state.letters, "d"] });
  };

  render() {
    return (
      <div>
        <button onClick={this.addLetter}>Click to add a letter</button>
        <h1>letters: {this.state.letters}</h1>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

Why this works:

By passing a new array reference to setState, you give React a clear signal that the state has changed. React compares the old and new state references, sees they're different, and triggers a component re-render to update your JSX with the updated letter list.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:52:48