axios 未使用上下文API eclipse 刻数据

6pp0gazn  于 2022-12-12  发布在  iOS
关注(0)|答案(1)|浏览(135)

我尝试使用API获取一些水果,并使用axios将它们显示到不同的组件中。问题是,它不起作用。数据不显示,我在控制台上没有得到任何记录。下面是我所做的,我使用上下文API。
水果数据文件

import React, { useState } from 'react';
import axios from 'axios';
import ApiContext from './ApiContext';

function FruitsData(props) {
const [fruits, setFruits] = useState([]);
const [selectedItem, setSelectedItem] = useState(null);

const fetchFruits = async () => {
    const response = await axios.get('/api/fruits');
    setFruits(response.fruits);
    console.log(response.fruits)
}

const selectItem = (id) => {
    const fruit = fruits.find(fruit => fruit.id === id);
    setSelectedItem(fruit);
}

const fetchItem = async (id) => {
    const response = await axios.get(`/api/fruit/${id}`);
    setSelectedItem(response.fruit);
}

return (
    <ApiContext.Provider value={[fruits, setFruits, selectedItem, selectItem, fetchFruits, fetchItem ]}>
        {props.children}
    </ApiContext.Provider>
);
}

export default FruitsData;

显示水果的组件

import ApiContext from '../../contexts/ApiContext';

function Training() {
let navigate = useNavigate();
const [fruits, setFruits] = useContext(ApiContext);

return (
    <div>
   {fruits && fruits.map((fruit) => (
   <FruitWidget fruit={fruit} key={fruit.id} />
    ))}
    </div>
);
}
export default Training;

App.js

<FruitsData>
        <Routes>
          <Route path="training" element={<Training />} />
          <Route path="fruit-details/:fruitId" element={<FruitDetails />} />
        </Routes>
      </FruitsData>
a2mppw5e

a2mppw5e1#

我会诚实的。没有读你的代码,你已经说了-在控制台上什么都没有,这意味着你的网址不正确

const fetchFruits = async () => {
    const response = await axios.get('/api/fruits'); // problem is here :)
    setFruits(response.fruits);
    console.log(response.fruits)
}

相关问题