axios React组件不显示获取的数据由于不正确的URL构造(404 Not Found)

tf7tbtn2  于 12个月前  发布在  iOS
关注(0)|答案(1)|浏览(106)

我正在使用Axios从Django REST Framework API获取数据。但是,该组件没有显示获取的数据,并且我在网络选项卡中遇到了404 Not Found错误。
Post.jsx

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function Post({ postId }) {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
console.log(postId)
  useEffect(() => {
    const fetchPost = async () => {
      setIsLoading(true);
      const url = `http://127.0.0.1:8000/myapi/posts/${postId}`;
      console.log('Constructed URL:', url);
      try {
        const response = await axios.get(`http://127.0.0.1:8000/myapi/posts/${postId}`); 
        setData(response.data);
      } catch (error) {
        setError(error);
        console.error('Axios request error:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPost();
  }, [postId]);

  return (
    <div>
      {isLoading ? (
        <p>Loading post...</p>
      ) : error ? (
        <p>Error fetching post: {error.message}</p>
      ) : (
        <article>
          <h2>{data.title}</h2>
          <p>{data.content}</p>
          <p>Author: {data.author.username}</p> // Assuming author data is included
          <p>Categories: {data.categories.map((category) => category.name).join(', ')}</p> // Assuming categories data
          <p>Tags: {data.tags.map((tag) => tag.name).join(', ')}</p> // Assuming tags data
          {/* Additional elements for comments, etc. */}
        </article>
      )}
    </div>
  );
}

export default Post;

字符串
API响应(直接访问时):

HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 1,
    "categories": [
        {
            "id": 1,
            "name": "test"
        }
    ],
    "tags": [
        {
            "id": 1,
            "name": "test"
        }
    ],
    "title": "Post1",
    "content": "asdijfoiajfoajsfopajsfpoasjfopajdfpoaodjfpadfiapoidfjapdfoajsdfpoaispdfajsdfopasfiojapdfjaopssdfjpajdfoiajpsfaf",
    "created_at": "2024-01-04T15:57:20.472070Z",
    "author": 1
}


App.js

import React from 'react';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import Posts from './components/Posts/Posts';
import Post from './components/Post/Post';
import {BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import './Global.css';

function App() {
  return (
    <Router>
      <Header />
      <main>
        <Routes>
          <Route path="/" element={<Posts />} />
          <Route path="/posts/:postId" element={<Post />} />
        </Routes>
      </main>
      <Footer />
    </Router>
  );
}

export default App;


故障排除步骤:
经验证的API响应:API终结点在直接访问时返回预期的数据结构。请检查网络请求:网络选项卡中的请求URL为http://127.0.0.1:8000/myapi/posts/undefined。这会导致404 Not Found错误。检查的状态值:由于请求失败,未填充数据状态。
其他信息:
React版本:email protected(https://stackoverflow.com/cdn-cgi/l/email-protection) Axios版本:“axios”:“^1.6.4”,Django REST Framework版本:djangorestframework==3.14.0浏览器和版本:Chrome版本120.0.6099.129什么可能导致错误的URL构造,以及如何确保正确的postId传递给组件?
任何指导或见解都将不胜感激!

qxgroojn

qxgroojn1#

问题是您的Post组件中的代码使用了prop postId而不是path参数:postId。当您在route组件的element prop中创建Post组件时,你没有将postId设置为prop。这就是为什么它总是undefined,你的代码不能像预期的那样工作。在这一点上,你混淆了react prop的概念。以及如何使用react-router-dom访问路径参数。
如果你想在你的函数式react组件中访问路径参数,比如你的:postId,你可以使用react-router-domuseParams钩子。这个钩子让你可以访问所有的路由参数。

解决方案:

App

...
function App() {
  return (
    <Router>
      <Header />
      <main>
        <Routes>
          <Route path="/" element={<Posts />} />
          // you define a path parameter :postId, which can get accessed in your Post component via useParams hook
          <Route path="/posts/:postId" element={<Post />} />
        </Routes>
      </main>
      <Footer />
    </Router>
  );
}

字符串
邮政

...
import { useParams } from 'react-router-dom';
// removed prop postId because it is not needed
function Post() {
  // get path param
  const { postId } = useParams()
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
console.log(postId)
  useEffect(() => {
    const fetchPost = async () => {
      setIsLoading(true);
      const url = `http://127.0.0.1:8000/myapi/posts/${postId}`;
      console.log('Constructed URL:', url);
      try {
        const response = await axios.get(`http://127.0.0.1:8000/myapi/posts/${postId}`); // Corrected URL
        setData(response.data);
      } catch (error) {
        setError(error);
        console.error('Axios request error:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPost();
  }, [postId]);

  return (...);
}

export default Post;

相关问题