【问题标题】:Use state from useContext component and access it from other component. It's fetching ok, but in the child component it gives an error使用来自 useContext 组件的状态并从其他组件访问它。它可以获取,但是在子组件中它给出了一个错误
【发布时间】:2021-03-08 05:12:48
【问题描述】:

我希望组件“主页”中的状态“用户”如下所示:console.log 工作正常且未定义。但是'map'循环给了我一个错误“TypeError:无法读取未定义的属性'map'”


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) 中,我有它:

{
"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>
  )

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

【问题讨论】:

    标签: javascript reactjs asynchronous async-await use-context


    【解决方案1】:

    问题

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

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

    解决方案

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

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

    【讨论】:

    • 谢谢,我不知道!!!!现在工作正常!祝你有美好的一天。
    猜你喜欢
    • 2021-02-28
    • 2021-11-13
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多