使用 Context API 和 useContext (React js) 传递值

Passing value by using Context API and useContext (React js)

我想传递我在 Login.jsx 组件中声明的 customerFlag 的值,并希望在Header.jsx。我正在使用 Context APIuseContext。基本上我在这里传递两个组件之间的值,你可以说是兄弟组件。但是 问题 是我得到的 customerFlag 值是 undefinedUserContext.Provider value={customerFlag} 标签。如果我做错了,请纠正我。我是react js的初学者

Login.jsx

import React, { createContext } from 'react';

      //Creating Context API
        const UserContext = createContext(null);
        .
        .
        .
        } else {
    
                 customerFlag='customer';
                 window.alert('Login successfull');
                 history.push('/home');
    
                }

return (
        <>
            
            {/* Providing the context to Header*/}

            <UserContext.Provider value={customerFlag} >
                <Header />
            </UserContext.Provider>

        </>
        )

Header.jsx

import React,{useContext} from 'react';
import {UserContext} from './Login';

const Header = () => {
    
    const context = useContext(UserContext)
    console.log(context);

return ();
}

customerFlag='customer'; 在 React 组件的生命周期中未知。这意味着如果 customerFlag 稍后更改,您的 Context 将不会注意到。

您需要使用 state 作为客户标志。例如:

const [cusomterFlag, setCustomerFlag] = useState('');

// ...

if(...) {
  // ...
} else {
  setCustomerFlag('customer');
  window.alert('Login successfull');
  history.push('/home');
}