如何使用React JS上下文API正确存储和检索数据?我拥有的代码无法正常工作

史前野兽

嗨,我是stackoverflow的新手,我是编程和学习React的新手。我试图从api端点获取数据并将其存储在上下文中后,存储用户信息。问题是我必须在每个网页中执行该功能才能访问其中存储的信息。我尝试useEffect在App.js中使用来获取数据并在标题和侧边栏中使用它,但是它仅在该文件中有效。我有路由器,因为我的网站上有多个页面。该代码是否存在任何问题,这些问题限制了在上下文中存储数据以及如何使用路由器正确执行此操作。

这些是我的密码

reducer.js

export const initialState = {
user: null,
};

export const actionTypes = {
    SET_USER: 'SET_USER',
};

const reducer = (state, action) => {
    // console.log(action);
    switch (action.type) {
        case actionTypes.SET_USER:
            return {
                ...state,
                user: action.user,
            };

        default:
            return state;
    }
};


export default reducer;

stateprovider.js

import React, { createContext, useContext, useReducer } from 'react';

export const StateContext = createContext();

export const StateProvider = ({ reducer, initialState, children }) => (
    <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </StateContext.Provider>

);

export const useStateValue = () => useContext(StateContext);

下面是我需要useEffect在每个页面中调用的功能,以便用户信息显示在标题和侧边栏中。

const [state, dispatch] = useStateValue()

const userInfo = async function userProfileInfo() {
    axiosInstance.get('accounts/data/view/').then((res) => {
        const currentUser = res.data;
        dispatch({
            type: actionTypes.SET_USER,
            user: currentUser,
        })

        })
}

useEffect(() => {
    userInfo()

}, [])

index.js

const routing = (
    <Router>
        
            <StateProvider initialState={initialState} reducer={reducer}>
                       
                <div className="body">
                    <Switch>
                        
                        <Route exact path="/signup" component={Signup} />
                        .
                        .
                        <Route exact path="/" component={App} />
                        <Route exact path="/myprofile" component={PostMyProfile} />
                        .
        </Switch>
       </div>
    </StateProvider>

        
    </Router>

header.js

const [state, dispatch] = useStateValue();
console.log(state.user)

<div className="header__info">
    <Avatar src= {state.user?.display_pic} alt=""/>
    <h4>{state.user?.username}</h4>
</div>

是否需要在每个页面中调用此函数?我认为应该有适当的方法来做到这一点。帮助将不胜感激。

谢谢

阿米拉·杜兰贾纳(Amila Dulanjana)

您不需要userInfo一次又一次地调用函数。您必须在开始时调用它,届时它将在状态中保存用户信息。因此,您可以根据需要从任何组件访问状态值。使用以下代码访问您的状态

const [state, dispatch] = useStateValue();

<p>{state.user}</p>

我已经更新了您的代码并将其添加到codesandbox中。在这里检查

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何提供正确的上下文,使AlertDialog的按钮正常工作

如何在getDerivedStateFromProps中使用React上下文API?

使用上下文API时如何在React JS中使用Match道具

我如何使用上下文在React中的类和功能组件之间共享状态?

如何在Golang Google数据存储包中正确使用上下文?

如何在 React js 中使用上下文 API 管理全局狀態

如何在 react app.js 文件中访问我的上下文 API 状态

如何存储用户拥有的数据?

如何使用我拥有的代码成功登录?

在 React JS 中使用路由器时如何使用上下文 API 传递状态

在Mac上使用SDL2设置OpenGL上下文3.3,无法正常工作

如何正确使用jQuery“上下文”

如何使用React.cloneElement设置上下文

React-如何使用cloneElement以便保留上下文

如何使用React Native将上下文绑定到异步存储

我可以在已经拥有 Redux 的项目中使用上下文 API 作为几乎另一个事实来源吗?

如何在我的React Form的构造函数中使用上下文?

如何使用来自上下文的数据控制React Re-Renders

此代码如何在具有reduce函数的上下文中工作?

如何使用jest和react-testing-library测试上下文提供的功能?

如何在React Router V4中使用上下文API?

如何使用 React 上下文 API 实现多语言站点

如何在App.js文件中使用React上下文?

如何为提供者使用带有多个值的React Hooks上下文

无法使用上下文挂钩将数据存储在商店中

在React Router旁边使用React API上下文

使用正确的上下文

无法使用具有2个Spring上下文的存储库和服务

无法正确使用上下文提供程序