简体   繁体   English

React 上下文不在全球范围内更新

[英]React Context Not Updating Globally

this is my Context, But I can't update its values globally.这是我的上下文,但我无法在全球范围内更新它的值。 It does change but not globally, and If I refresh the page for example, it goes to the default values again.它确实发生了变化,但不是全局变化,例如,如果我刷新页面,它会再次进入默认值。 What I am doing wrong?我做错了什么?

import React, { useReducer } from 'react'

const initialState = {
    user: 'magnus',
    isAuth: false
};

const actions = {
    SET_USER: "SET_USER",
    SET_AUTH: "SET_AUTH"
};

const reducer = (state,action) => {
    switch(action.type) {
        case actions.SET_USER:
            return {
                user: action.user
            };
        case actions.SET_AUTH:
            return {
                isAuth: action.setAuth
            };
        default:
            return state;
    }
};

export const UserContext = React.createContext();

const Provider = ({children}) => {
    const [state, dispatch] = useReducer(reducer, initialState);
    
    const value = {
        user: state.user,
        isAuth: state.isAuth,
        setUser: (user) => {
            dispatch({ type: actions.SET_USER, user});
        },
        setAuth: (auth) => {
            dispatch({type: actions.SET_AUTH, auth});
        }
    };

    return (
        <UserContext.Provider value={value}>
            {children}
        </UserContext.Provider>
    );

};

export default UserContext;
export { Provider };

Im using this on the other component:我在另一个组件上使用它:

const { user, isAuth, setUser } = useContext(UserContext);

    return(
        <div>
        <h3>{user}</h3>
        <h3>{isAuth ? 'ok' : 'not ok'}</h3>
        <button onClick={() => setUser('brutus')}>change</button>
        </div>
    )

It is updating the user but only in this component, If I reload the page for example, it keeps saying 'magnus' instead of 'brutus'.它正在更新用户但仅在此组件中,例如,如果我重新加载页面,它会一直说“magnus”而不是“brutus”。

This is my index.js:这是我的 index.js:

<Provider>
  <App />
</Provider>

App.js:应用程序.js:

<BrowserRouter>
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/dashboard" element={<Dashboard />} />
                </Routes>
            </BrowserRouter>

Can someone please help me?有人可以帮帮我吗?

The problem is you export UserContext twice问题是您两次导出UserContext

export const UserContext = React.createContext();

export default UserContext;

So just keep the 1st one and import into component:所以只保留第一个并导入到组件中:

import { UserContext } from './UserContext'

Here is the working example这是工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM