gpt4 book ai didi

reactjs - 如何在 react 中在上下文提供程序中使用 axios get 调用

转载 作者:行者123 更新时间:2023-12-04 08:35:02 27 4
gpt4 key购买 nike

我想调用以获取用户信息并在整个应用程序的不同组件中使用它,所以我使用 react.Context 并且我设法在组件之间移动一个字符串但是当我尝试使用 axios.get 时无法将数据获取到另一个组件,这里是上下文代码:

import React, { createContext } from 'react';
import axios from 'axios';

export const userContext = createContext();

export const UserProvider = (props) => {
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${localStorage.getItem('access')}`,
'Accept': 'application/json'
}
};
const res = axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config)
return(
<userContext.Provider value= { res }>{props.children}</userContext.Provider>
);
}
有人可以告诉我我在这里做错了什么吗

最佳答案

如果您能处理 state 会更易于管理。以无忧无虑的方式。而不是通过 res我估计是你的状态,直接到Provider .我认为,及时,如果您有多个 state您想添加到您的 User语境。你也需要通过它们作为 value .那将是不灵活的。
我建议你像这样管理它们:-

  • 有奉献User上下文文件夹:src/contexts/User
  • src/contexts/User/UserContext (创建 User 上下文)
  • import { createContext } from "react";

    export const UserContext = createContext();

  • src/contexts/User/UserReducer (句柄 state 更新)
  • export default (state, action) => {
    switch (action.type) {
    case "SET_USER":
    return {
    ...state,
    user: action.payload
    };
    case "SET_ERROR":
    return {
    ...state,
    error: action.payload.error,
    message: action.payload.message
    };
    case "SET_LOADING":
    return {
    ...state,
    loading: action.payload
    };
    default:
    return state;
    }
    };

  • src/contexts/User/UserAction (句柄 actionstate 进行了处理。基本上是您对 state 进行更改所需的任何内容)
  • import axios from "axios";

    // Set Loading
    export const setLoading = (dispatch, status) =>
    dispatch({ type: "SET_LOADING", payload: status });

    // Set Error
    export const setError = (dispatch, error) =>
    dispatch({
    type: "SET_ERROR",
    payload: { error: error.status, message: error.message }
    });

    // Set User (get user info)
    export const getUser = async dispatch => {
    setLoading(dispatch, true);

    // do fetch
    await axios
    .get(`https://jsonplaceholder.typicode.com/users/1`)
    .then(res => {
    const result = res.data;

    // set user info
    dispatch({
    type: "SET_USER",
    payload: result
    });
    })
    .catch(error => {
    const result = error;

    // set error if has any
    dispatch({
    type: "SET_ERROR",
    payload: {
    error: true,
    message: result
    }
    });
    });
    };

  • src/contexts/User/UserState (处理 state 初始化。如果有的话,您可以稍后在下面的 const initialState 中添加更多或初始化更多状态。此外,您以后不需要添加更多 value。)
  • import React, { useContext, useReducer } from "react";
    import { UserContext } from "./UserContext";
    import UserReducer from "./UserReducer";

    export const useUser = () => {
    const { state, dispatch } = useContext(UserContext);
    return [state, dispatch];
    };

    export const UserState = ({ children }) => {
    const initialState = {
    user: {},
    loading: false,
    error: false,
    message: ""
    };

    const [state, dispatch] = useReducer(UserReducer, initialState);

    return (
    <UserContext.Provider
    value={{
    state: state,
    dispatch: dispatch
    }}
    >
    {children}
    </UserContext.Provider>
    );
    };

    然后你可以像这样使用它们:-
  • 确保encapsulate任何 component你想使用 User上下文(这将在 App.js 中)
  • App.js :-
  • import React from "react";
    import { UserState } from "./contexts/User/UserState";
    import Demo from "./Demo";
    import "./style.css";

    export default function App() {
    return (
    <UserState>
    <Demo />
    </UserState>
    );
    }

  • 您可以使用任何 state initializedUserState通过使用 useState :-
  • Demo.js ( App.js 子组件):-
  • import React, { useEffect } from "react";
    import { useUser } from "./contexts/User/UserState";
    import { getUser, setLoading } from "./contexts/User/UserAction";
    import "./style.css";

    const Demo = () => {
    const [userState, userDispatch] = useUser();
    const { user, loading, error, message } = userState;

    // get user info handler
    const getUserInfoHandler = async () => {
    await getUser(userDispatch);
    setLoading(userDispatch, false);
    };

    // get user info
    useEffect(() => {
    getUserInfoHandler();
    }, []);

    return (
    <div>
    {loading && <p>Loading...</p>}
    {error && <p>{message}</p>}
    <p>User name: {user.name}</p>
    </div>
    );
    };

    export default Demo;

    您可以在 sandbox 中看到工作代码。

    关于reactjs - 如何在 react 中在上下文提供程序中使用 axios get 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64841268/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com