使用 useContext 组件的状态并从其他组件访问它。可以正常获取,但是在子组件中会报错

Use state from useContext component and access it from other component. It's fetching ok, but in the child component it gives an error

我想要组件 'Home' 中的状态 'user' 如下所示: console.log 工作正常并且不是未定义的。但是 'map' 循环给我一个错误“TypeError: Cannot read 属性 'map' of undefined”


import {UserContext, UserProvider} from './context/UserContext'

const Home = () => {

  const [user, setUser] = useContext(UserContext)

  console.log(user)

  return(
    <div className="css-home">
      <div className="css-home-div-find">
        <input className="css-home-find" placeholder="Typo here to find someone" type="text"/>
      </div>
      <div className="css-overflow css-home-friends">
        {
          user.friends.map(friend => (
            <FriendsSummary/>
          ))
        }           
      </div>
    </div>
  )
}

在console.log(用户)中,我有:

{
"user": [
{
"_id": "6045352a4eb4f70ff41b0f73",
"date": "2021-03-07T20:18:45.893Z",
"name": "Shrek",
"email": "shrek@gmail.com",
"hate": "Corn",
"friends": [
       {
         "_id": "6045352a4eb4f70ff41b0f74",
         "name": "Donada",
         "hate": "skol",
         "voted": false,
         "votes": {
            "heart": 10,
            "heartbroken": 2,
            "fire": 130,
            "horse": 12,
            "eye": 12412
          }
       },
       {
         "_id": "6045352a4eb4f70ff41b0f75",
         "name": "Otto",
         "hate": "it",
         "voted": false,
         "votes": {
            "heart": 1,
            "heartbroken": 2,
            "fire": 2,
            "horse": 12,
            "eye": 123
          }
       }
    ],
"__v": 0
}]}

我的 useContext 是:

  useEffect(() => {
    getUser()
  },[])

  const[user, setUser] = useState({})

  const getUser = async () => {
    const response = await fetch('http://localhost:8081/users/get_friends')
    const data = await response.json()
    setUser(data.user[0])  
  } 

  return(    
    <UserContext.Provider value={[user, setUser]}>
      {props.children}
    </UserContext.Provider>
  )

我认为这可能是一些异步问题,但我不知道如何解决...

问题

在获取数据和更新状态之前,您的初始状态没有 friends 数组来映射初始渲染。

const[user, setUser] = useState({});

解决方案

提供有效的初始状态。初始状态应包括在初始渲染中引用的任何嵌套初始状态。如果您的 UI 正在映射一个 user.friends 数组,那么它需要可用。

const[user, setUser] = useState({
  friends: [],
});