useContext导致黑屏

useContext causing blank screen

该应用使用 useContext 进行状态管理,并使用 axios 向 API 发出获取请求以接收数据。最初我没有使用 useContext 但后来意识到状态将在以后的多个组件中需要并且道具会很混乱。该应用程序在使用 useContext 之前运行良好,现在我收到一个空白屏幕并且没有错误消息。

ThemeContext.js

import {useState, useEffect, createContext} from 'react'
import axios from 'axios'
const ThemeContext = createContext()

const ThemeContextProvider = props => {

  const [students, setStudents] = useState([])
  const [loading, setLoading] = useState(false)


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

  const getStudents = async () => {
    try {
          const res = await axios.get('https://api.hatchways.io/assessment/students')
          setStudents(res.data.students)
          setLoading(true)
    }
    catch (err) {
      console.log(err.message)
    }
  }

  return (
      <ThemeContextProvider.Provider value={{students, loading}}>
          {props.children}
      </ThemeContextProvider.Provider>
  )

}

export {ThemeContextProvider, ThemeContext}

Students.js

import {useContext} from 'react'
import {ThemeContext} from './themeContext'


const Students = props => {

  const {students, loading} = useContext(ThemeContext)  
 
  return (
    <div>
        {loading &&
         students.map((student) =>(
                <div className="student-profile-container">

                      <div className="student-profile-image">
                        <img key={student.id} src={student.pic} alt="student profile avatar"/>
                      </div>
                      <div className="student-profile-info">
                          <h1 className="student student-name">{student.firstName} {student.lastName}</h1> 
                          <p className="student student-info">Email: {student.email}</p>
                          <p lassName="student student-info">Company: {student.company}</p>
                          <p className="student student-info">Skill: {student.skill}</p>
                          <p className="student student-info">Average: {student.average}%</p>

                       
                      </div>
                    
                </div>
               
            ))
        }
    </div>
  );
}

export default Students;

您似乎混淆了 ThemeContextThemeContextProvider。更改 ThemeContextProvider 的 return 值应该可以解决您的问题。

<ThemeContext.Provider value={{students, loading}}>
   {props.children}
</ThemeContext.Provider>