所以,这是一个奇怪的问题。昨天一切正常,我可以看到显示的类别对象,我可以在类别之间切换,但是今天我想继续项目,但是数据没有显示,我什至在控制台中看不到对象。可能是什么问题,是否在 Fetch 中,我真的非常感谢您的帮助
import React, {useState, useEffect} from 'react'
import URL from '../utilis/URL'
const BookContext = React.createContext();
export default function BooksProvider({ children }) {
const [data, setData] = useState([])
const [currentSelectedCategory, setCurrentSelectedCategory] = useState([]);
const handleSelectCategory = (category) => {
setCurrentSelectedCategory(data[category]);
};
const fetchData = async () => {
const response = await fetch(URL);
const result = await response.json();
console.log(data.result)
setCurrentSelectedCategory(result[Object.keys(result)[0]]);
setData(data);
};
useEffect(()=>{
fetchData();
},[])
return (
<BookContext.Provider value={{ data, handleSelectCategory, setCurrentSelectedCategory, currentSelectedCategory }}>
{children}
</BookContext.Provider>
);
}
export {BookContext, BooksProvider}
import React,{useState, useEffect} from 'react'
import './Home.css'
import Books from './Books'
import { BookContext } from "../../context/books";
const Home = () => {
const {data, handleSelectCategory, currentSelectedCategory } =React.useContext(BookContext)
return (
<div className='books__container' >
<h1 className='categories'>Categories</h1>
{Object.keys(data).map((key, index)=>{
let books = data[key];
return (
<>
<span key={key} onClick={() => handleSelectCategory(key)} className='books__list' >
{books[0].category}
</span>
</>
);})}
<Books category={currentSelectedCategory} />
</div>
)
}
export default Home
答案 0 :(得分:2)
这没有任何作用:
console.log(data.result)
因为 data
是一个空数组(并且数组无论如何都没有 result
属性):
const [data, setData] = useState([])
这没有任何作用:
setData(data);
因为您只是将状态更新为本身,这不会改变任何内容并且可能不会触发任何重新渲染。 (尽管即使是这样,渲染也会映射 data
的元素,这仍然是一个空数组。)
您可能想通过 API 将 data
状态对象设置为 result
?:
setData(result);