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

如何在React组件中渲染含列表的对象并实现自动更新?

Solution for Auto-Updating Hobby List in React Component

Got it, let's get your Hobbies component set up so it renders your data properly and updates automatically when you add new hobbies! Here's a complete, working implementation:

class Hobbies extends React.Component {
  constructor(props) {
    super(props);
    // Store your data in component state (critical for auto-updates)
    this.state = {
      name: 'David',
      hobby: ['diving', 'traveling', 'Eating']
    };
    // Bind the event handler to keep correct `this` context
    this.addNewHobby = this.addNewHobby.bind(this);
  }

  addNewHobby() {
    const inputValue = this.hobbyInput.value.trim();
    if (!inputValue) return; // Don't add empty hobbies

    // Update state correctly (never mutate state directly!)
    this.setState(prevState => ({
      hobby: [...prevState.hobby, inputValue]
    }));

    // Clear the input after adding
    this.hobbyInput.value = '';
  }

  render() {
    return (
      <div>
        <h3>{this.state.name}'s Hobbies:</h3>
        {/* Render the hobby list dynamically */}
        <ul>
          {this.state.hobby.map((hobby, index) => (
            <li key={index}>{hobby}</li>
          ))}
        </ul>

        {/* Add a way to input new hobbies (demo for auto-update) */}
        <div style={{ marginTop: '10px' }}>
          <input
            type="text"
            ref={input => this.hobbyInput = input}
            placeholder="Type a new hobby..."
          />
          <button onClick={this.addNewHobby}>Add Hobby</button>
        </div>
      </div>
    );
  }
}

Key Things to Note:

  • Use React State, Not Plain Objects: Your original MyData variable won't trigger re-renders when modified. By moving the data into this.state, React will automatically update the UI whenever you call setState().
  • Dynamic List Rendering: Instead of hardcoding <li> elements, we use Array.map() to loop through the hobby array in state. The key prop helps React track list items efficiently (use a unique ID instead of index if your hobbies might be duplicated).
  • Safe State Updates: Never mutate state directly (like this.state.hobby.push(...)). Instead, create a new array with the spread operator ([...prevState.hobby, newItem]) and pass it to setState(). Using the functional form of setState ensures we're always working with the latest state value.
  • Interactive Demo: The input and button show how adding a new hobby instantly updates the list—no extra work needed, because we're updating state correctly.

If your MyData is supposed to come from a parent component's props instead of being hardcoded, you can initialize state with props.MyData and add a componentDidUpdate method to sync state with props if needed. But for your current use case, the above code works perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:24:02