在JSX中展示状态列表: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()
Theconcatmethod 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

