简体   繁体   English

"为什么我在 selectedUser 中有未定义?"

[英]Why do I have undefined in selectedUser?

Why do I have undefined in selectedUser?为什么我在 selectedUser 中有未定义? After all, I go through the find method through the users array and the first id of the users array should be written to selectedUser毕竟我是通过users数组遍历find方法,users数组的第一个id应该写入selectedUser

function App() { 
const [selectedUserId, setSelectedUserId] = useState(null)
const [users,setUsers] = useState([])
const selectedUser = users.find(u => u.id === selectedUserId)
console.log(users)
console.log(selectedUser)

useAsyncEffect(async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const data = await res.json()
  setUsers(data)
}, [])

const onUserClick = (userId) => {
  setSelectedUserId(userId)
}

return (
  <div>
  { selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user= 
 {selectedUser}  />
  }
  </div>
)
}

You can use a loading state to determine when the async function is done and only then you can set the selected user.您可以使用加载状态来确定异步功能何时完成,然后才能设置所选用户。 Otherwise, it remains set to 'null' when the 'return' is rendered.否则,当“return”被渲染时,它仍然设置为“null”。

Below is pseudo code.下面是伪代码。

 function App() { 
    const [selectedUserId, setSelectedUserId] = useState(null)
    const [users,setUsers] = useState([])
    const selectedUser = users.find(u => u.id === selectedUserId)
    const [loading, setLoading] = useState(false)

    console.log(users)
    console.log(selectedUser)
    
    useAsyncEffect(async () => {
      setLoading(true)
      const res = await fetch('https://jsonplaceholder.typicode.com/users')
      const data = await res.json()
      setUsers(data)
      setLoading(false)
    }, [])
    
    const onUserClick = (userId) => {
      setSelectedUserId(userId)
    }
   if (loading){
      return "Loading..."
      // you can use a nicer loader component here
   }
    
    return (
      <div>
      { selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user= 
     {selectedUser}  />
      }
      </div>
    )
    }

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

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