【问题标题】:Passing value by using Context API and useContext (React js)使用 Context API 和 useContext (React js) 传递值
【发布时间】:2021-05-08 10:16:45
【问题描述】:

我想传递我在 Login.jsx 组件中声明的 customerFlag 的值,并希望在 Header.jsx 中访问该值.我正在使用 Context APIuseContext。基本上在这里我在两个组件之间传递值,你可以说是兄弟组件。但是 problem 是我在 UserContext.Provider value={customerFlag} 标签下得到 customerFlag 值是 undefined。如果我做错了,请纠正我。我是 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 ();
}

【问题讨论】:

    标签: javascript reactjs react-context use-context


    【解决方案1】:

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

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

    const [cusomterFlag, setCustomerFlag] = useState('');
    
    // ...
    
    if(...) {
      // ...
    } else {
      setCustomerFlag('customer');
      window.alert('Login successfull');
      history.push('/home');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-10
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 2020-11-26
      • 2020-11-21
      • 2021-03-19
      相关资源
      最近更新 更多