javascript - 如何使用 react js context api 正确存储和检索数据?我的代码没有按预期工作

标签 javascript reactjs react-native jsx react-context

我正在学习 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>
是不是每个页面都要调用这个函数?我想应该有一个适当的方法来做到这一点。

最佳答案

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

const [state, dispatch] = useStateValue();

<p>{state.user}</p>
我已更新您的代码并将其添加到代码沙箱中。请查看here

关于javascript - 如何使用 react js context api 正确存储和检索数据?我的代码没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64598211/

相关文章:

javascript - 工具提示嵌套在<label>中,防止 'mousedown'触发输入:active

JavaScript:在鼠标指针下突出显示/选择单词

javascript - 同一路线的两个请求 emberjs 2

javascript - 我的 React 应用程序没有显示我创建的组件,我找出了原因

javascript - native react : calling multiple functions onPress

javascript - 我正在创建的窗口在屏幕周围跳跃,为什么?

javascript - Redux 如何保证没有竞争条件?

meteor - Meteor React.js 教程第 2 部分中的应用程序崩溃

React-Native:如何知道渲染何时完成

java - 更改react-native项目中android和ios的入口文件路径