如何在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
MyDatavariable won't trigger re-renders when modified. By moving the data intothis.state, React will automatically update the UI whenever you callsetState(). - Dynamic List Rendering: Instead of hardcoding
<li>elements, we useArray.map()to loop through thehobbyarray in state. Thekeyprop helps React track list items efficiently (use a unique ID instead ofindexif 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 tosetState(). Using the functional form ofsetStateensures 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
相关产品推荐
相关产品推荐

