Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

reactjs - How to dynamically render a stateful component in React

How does one go about dynamically rendering a stateful component that takes in props that can change after render? I have tried storing components in state and then mapping out the state however the components do not update when the props passed into them has changed. Example:

export default App(props){
const [name, setName] = useState(null)
const [articles, setArticles] = useState([])

return (
      {articles.map((article) => {article})}
      <input type="text" value={name} onChange={e => setName(e.target.value)}/>
      <button type="button" onClick={() => setArticles([...articles, <Article name={name}/>])}}>Add Article</button>
)

}
export default Article(props){
    return (
       <p>props.name</p>
)

}

In my example, when I update the name state by changing the input field, none of the rendered articles update to reflect this change, only new additions when the add article button is pressed after the name has been changed, I want them to update as the state changes, how do I do this?

question from:https://stackoverflow.com/questions/65541050/how-to-dynamically-render-a-stateful-component-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a clean-up of your code that basically produces a "To Do" list. Some mistakes you had...

  1. Multiple default exports
  2. Unnecessary use of map
  3. Lack of curly braces around props.name
export default function App(props){
  const [name, setName] = useState(null)
  const [articles, setArticles] = useState([])
  
  return (
<>
  {articles}
  <input type="text" value={name} onChange={e => setName(e.target.value)}/>
  <button type="button" onClick={() => setArticles(
    [...articles, <Article name={name}/>]
  )}>Add Article</button>
</>
)
  
  }

export function Article(props){  
  return (
    <p>{props.name}</p>
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...