猿问

reactJS - 使用 Axios GET 请求的 useEffect() 空响应

这是我尝试使用 Axios 请求从后端获取数据的地方:


 const [models, setModels] = useState([]);


const sponsor_id = localStorage.getItem('sponsor_id');

 

  useEffect(() => {

        api.get('models', { sponsor_id }).then(response => {

            setModels(response.data);

        });

    }, []);


这是我的后端,它应该从数据库返回数据:


module.exports = {

    async index(request, response) {

        const { sponsor_id } = request.body;


        const models = await connection('model').select('*').where('sponsor_id', sponsor_id);


        return response.json(models);

    },


但是前端的响应是空的。它应该返回一些数据。我希望有人能帮助我。


慕桂英4014372
浏览 183回答 1
1回答

DIEA

请检查这个例子。这里我在 useEffect 中调用 axios 并在 ui 中显示响应数据。import React, {useEffect, useState} from "react";import axios from 'axios';function PostListPage() {&nbsp; &nbsp; const [posts, setPost] = useState([]);&nbsp; &nbsp; let signal = axios.CancelToken.source();&nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; &nbsp; let isSubscribed = true;&nbsp; &nbsp; &nbsp; &nbsp; axios.get(`https://jsonplaceholder.typicode.com/posts`, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cancelToken: signal.token,&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(res => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const posts = res.data;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setPost(posts);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).catch(err => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(err);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; return function cleanup() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; isSubscribed = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; signal.cancel('Api is being canceled');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }, []);&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <React.Fragment>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; posts.map(post => <li key={post.id}>{post.title}</li>)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; &nbsp; &nbsp; </React.Fragment>&nbsp; &nbsp; );}export default PostListPage;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答