【问题标题】:Uncaught (in promise) Error: Request failed with status code 404 when going to the profile未捕获(承诺中)错误:访问配置文件时请求失败,状态码为 404
【发布时间】:2022-01-26 01:01:19
【问题描述】:

在使用 API github 时出现了这样的问题。转到个人资料时我无法获取数据,但搜索时一切正常。我不明白为什么

出现这个错误

enter image description here

试图显示用户数据时,但搜索时却没有这样的错误

enter image description here

当我转到个人资料时

enter image description here

代码

import React from 'react'
import { Link, useParams } from 'react-router-dom';
import { useContext, useEffect, Fragment } from 'react';
import { GithubContext } from '../context/github/githubContex';

export const Profile = () => {

    const {getUser, getRepos, loading, user, repos} = useContext(GithubContext)
    const urlName = useParams()


    useEffect(() => {
        getUser(urlName)
        getRepos(urlName)

        console.log('Effect');
    },[])

    if (loading) {
        return <p className='text-center'>Загрузка...</p>
    }   

    const {
        name, company, avatar_url,
        location, bio, blog, 
        login, html_url, followers,
        following, public_repos, publick_gists

    } = user


    return(
        <Fragment>
            <Link to='/' className='btn btn-link'> На головну</Link>

            <div className='card mb-4'>
                <div className='card-body'>
                    <div className='row'>
                        <div className='col-sn-3 text-center'>
                            <img src={avatar_url} alt={name}></img>
                            <h1>{name}</h1>
                            {location && <p>Місце знаходженя: {location} </p>}
                        </div>
                        <div className='col'>
                            {
                                bio && <Fragment>
                                    <h3>BIO</h3>
                                    <p>{bio}</p>
                                </Fragment>
                            }
                            <a 
                                href={html_url}
                                target="_blank"
                                rel="noopener noreferrer" 
                                className='btn btn-dark'
                            >Відкрити профіль</a>
                            <ul>
                                {login && <li>
                                    <strong>Username: </strong> {login}
                                </li> }

                                {company && <li>
                                    <strong>Компания: </strong> {login}
                                </li> }


                                {blog && <li>
                                    <strong>Website: </strong> {login}
                                </li> }
                                
                                <div className='badge badge-primary'>
                                    Підписники: {followers}
                                </div>

                                <div className='badge badge-success'>
                                    Підписаний: {following}
                                </div>

                                <div className='badge badge-info'>
                                    Репозиторій: {public_repos}
                                </div>

                                <div className='badge badge-dark'>
                                    Gists: {publick_gists}
                                </div>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </Fragment>
    )


}

import React, {useReducer} from "react"
import axios from 'axios'
import { CLEAR_USERS, GET_REPOS, GET_USER, SEARCH_USERS, SET_LOADING } from "../types"
import { GithubContext } from "./githubContex"
import { githubReducer } from "./githubReducer"

const CLIENT_ID = process.env.REACT_APP_CLIENT_ID
const CLIENT_SECRET = process.env.REACT_APP_CLIENT_SECRET 

const withCreads = url => {
    return `${url}client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}`
}

// console.log(CLIENT_ID, 'asd', CLIENT_SECRET)

export const GithubState = ({children}) => {
    const initialState = {
        user: {},
        users: [],
        loading: false,
        repos: []
    }
    const [state, dispatch] = useReducer(githubReducer, initialState)

    const search = async value => {
        setLoading()

        const response = await axios.get(
           withCreads(`https://api.github.com/search/users?q=${value}&`)
        )

        dispatch({
            type: SEARCH_USERS,
            payload: response.data.items
        })
    }

    const getUser = async name => {
        setLoading()

        const response = await axios.get(
            withCreads(`https://api.github.com/users/${name}?`)
        )

        console.log('name', name)

        dispatch({
            type: GET_USER,
            payload: response.data
        })
    }

    const getRepos = async name => {
        setLoading()

        const response = await axios.get(
            withCreads(`https://api.github.com/users/${name}/repos?per_page=5&`)
        )

        dispatch({
            type: GET_REPOS,
            payload: response.data
        })
    }

    const clearUsers = () => dispatch({type: CLEAR_USERS})
    
    const setLoading = () => dispatch({type: SET_LOADING})

    const {user, users, repos, loading} = state

    return (
        <GithubContext.Provider value={{
            setLoading, search, getUser, getRepos, clearUsers,
            user, users, repos, loading
        }}>
            {children}
        </GithubContext.Provider>
    )
}

【问题讨论】:

    标签: javascript reactjs api github


    【解决方案1】:

    您将对象传递给getUser 而不是string,因此您应该将urlName 作为useParams 的属性。

    const { urlName } = useParams()
    

    您还需要将key/value 属性传递给路由组件的子组件,如下所示:

    // set param with unique name to route's path
    <Route path="/user/:urlName" />
    
    // access the 'key/value' params after transition to the route component inside it's children
    const {urlName} = useParams()
    

    这样,如果您想拥有动态路由路径,您可以将 :urlName 设置为您的 Link 组件,例如:

    const userName = "Johb"
    <Link to={`/user/${userName}`}
    

    【讨论】:

    • 它有所帮助,但并不完全。就是这样,一个错误丢失了imgur.com/a/eQV9F5p
    • 请关注更新后的回答
    • 感谢帮助我在 hook useMatch 的帮助下解决了这个问题
    • @YuraOleksiiko 完美尝试。所以useRouteMatch 如果您的路线没有实际呈现,将会很有用
    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 2018-08-09
    • 2019-08-03
    • 2020-12-01
    • 2020-07-30
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多