【问题标题】:Toggle button doesnt react with useContext切换按钮不与 useContext 反应
【发布时间】:2021-09-17 15:46:34
【问题描述】:

我正在尝试使用 useContext 切换我的导航栏按钮,但没有任何反应。 我创建了一个 ButtonContext 文件并声明了一个 isPressed 变量。 在 App.tsx 中,我使用 useCallBack 创建,在活动时会切换 isPressed。

App.tsx:

const [isPressed, setIsPressed] = useState(false);
const toggleButton = useCallback(()=>{
    setIsPressed(!isPressed);
},[]);

const contextValue = {
    isLoggedIn: isLoggedIn,
    login: login,
    logout: logout,
    isPressed: isPressed,
    toggleButton: toggleButton
}
return (
    <AuthContext.Provider
        // Value will listening for isLoggedIn state changes
        value={contextValue}>
        <div className="App">
            <BrowserRouter forceRefresh={true}>
                <Switch>
                    <Route exact path="/">
                        <Home/>

ButtonContext.tsx:

export const ToggleButton = createContext({
isPressed:false,
toggleButton: ()=>{}
})

LoginBar.tsx:

import {ToggleButton} from "../../../shared/context/ButtonContext";

const LoginBar: React.FC = () => {

const hamburgerButton = useContext(ToggleButton);
const auth = useContext(AuthContext);

const [pressed, setIsPressed] = useState(false);

return (
    <React.Fragment>
        <div className="toggle-button">
            <span className="bar"> </span>
            <span className="bar"> </span>
            <span className="bar"> </span>
        </div>
        {hamburgerButton.isPressed && <MobileNavbar/>}
        {!hamburgerButton.isPressed && <div
            className={hamburgerButton.isPressed ? 'mobile-navbar' : 'login-bar'}>
            <ul>
                {!auth.isLoggedIn && <li><HeaderBtn btnName="Login" route="/login"/> 
              </li>}
                {auth.isLoggedIn && <li><HeaderBtn btnName="My cart" route="/cart"/> 
              </li>}
                {auth.isLoggedIn && <li><HeaderBtn btnName="Logout" route="/"/></li>}
            </ul>
        </div>}

    </React.Fragment>
)

}

【问题讨论】:

    标签: react-native use-context


    【解决方案1】:

    在数组中添加isPressed

    const toggleButton = useCallback(()=>{
        setIsPressed(!isPressed);
    },[isPressed]);
    

    你需要像这样访问上下文:

    const {toggleButton} = useContext(AuthContext);
    

    要更改值,您必须调用 toggleButton()

    【讨论】:

    • 非常感谢,但仍然没有解决问题。
    • 如果我使用 {toggleButton} 访问 isPressed 变量会有多糟糕?我是 React 的新手,所以很抱歉我没听懂
    • 你可以通过const {isPressed} = useContext(AuthContext);访问isPressed 我已经创建了一个反应样本codesandbox.io/s/react-playground-forked-3q3fe?file=/Login.js
    猜你喜欢
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2019-05-25
    • 2020-10-03
    相关资源
    最近更新 更多