📌  相关文章
📜  如何在反应中使用钩子在加载时调用 api - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:38.552000             🧑  作者: Mango

代码示例1
function User() {
  const [firstName, setFirstName] = React.useState(null);
  const [lastName, setLastName] = React.useState(null);
  
  React.useEffect(() => {
    fetch('https://randomuser.me/api/')
      .then(results => results.json())
      .then(data => {
        const {name} = data.results[0];
        setFirstName(name.first);
        setLastName(name.last);
      });
  }, []); // <-- Have to pass in [] here!

  return (
    
Name: {!firstName || !lastName ? 'Loading...' : `${firstName} ${lastName}`}
); } ReactDOM.render(, document.querySelector('#app'));