简体   繁体   English

如何使用 useState object 数组在 React 中添加 HTML 元素 onClick?

[英]How to add HTML element onClick in React with a useState object array?

I am fetching random users from an API and putting them in a useState object array, this works as I checked in console.我正在从 API 中获取随机用户并将它们放入 useState object 数组中,这在我在控制台中检查时有效。 The issue is I want to display a new user on button click but it doesn't work, however if I write the same JSX code outside of an onClick, it works, let me demonstrate:问题是我想在按钮单击时显示一个新用户,但它不起作用,但是如果我在 onClick 之外编写相同的 JSX 代码,它可以工作,让我演示一下:

This doesn't work这不起作用

  const addUser = () => {
    object.map((item) => {
      return (
      <div>
        <h1>{item.firstName}</h1>
        <h1>{item.age}</h1>
        <h1>{item.gender}</h1>
        <img src={item.img} alt="" />
      </div>
      )
    })
  }

  return (
    <div className="App">
     <button onClick={addUser}
      >+</button>
    </div>
  );

This works:这有效:

 return (
    <div className="App">
      {object.map((item) => {
        return (
          <div>
            <h1>{item.firstName}</h1>
            <h1>{item.age}</h1>
            <h1>{item.gender}</h1>
            <img src={item.img} alt="" />
          </div>
        )
      })}
    </div>
  );

Here is the full code if it matters:如果重要的话,这里是完整的代码:

function App() {
  const URL = "https://randomuser.me/api/"

  const [object, setObject] = useState([{ firstName: 'jon', age: 20, gender: 'male', img: 'none' }])


  useEffect(() => {
    fetch(URL)
      .then(res => res.json())
      .then(data => {
        const result = data.results[0]
        const obj = {
          firstName: result.name.first,
          age: result.dob.age,
          gender: result.gender,
          img: result.picture.large
        }
        setObject(prevData => prevData.concat(obj))

      })
  }, [])

  const addUser = () => {
    object.map((item) => {
      return (
      <div>
        <h1>{firstName}</h1>
        <h1>{item.age}</h1>
        <h1>{item.gender}</h1>
        <img src={item.img} alt="" />
      </div>
      )
    })
  }

  console.log(object[0])
  console.log(object[1])


  return (
    <div className="App">
     <button onClick={() => addUser}
      >+</button>
    </div>
  );
}

export default App;
  1. Two problems with your code are您的代码有两个问题是
  • You are expecting a button onClick function to return DOM elements and somehow render them in your app.您期待一个按钮 onClick function 返回 DOM 元素并以某种方式在您的应用程序中呈现它们。
  • If you really want to show users only when the button is clicked, you can set a flag that turns true when clicked on the button and then show users list, returning DOM elements on button onClick won't render them.如果您真的想仅在单击按钮时显示用户,您可以设置一个在单击按钮时变为 true 的标志,然后显示用户列表,在按钮 onClick 上返回 DOM 元素不会呈现它们。
  1. Not wrapping addUser in return.不包装 addUser 作为回报。

    const addUser = () => { return ( // existing code ) } const addUser = () => { return ( // 现有代码 ) }

For code, you can checkhere有关代码,您可以在此处查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM