【问题标题】:how to reverse a state in react context如何在反应上下文中反转状态
【发布时间】:2020-03-24 12:12:25
【问题描述】:

如何将状态从 true 更改为 false 并将 false 更改为 true?

这是我的代码:

import React, { createContext , useState } from 'react';

export const RegContext = createContext();

const RegContextProvider = (props) => {
    const[mode, setMode] = useState([
        { showing: false }
    ]);

    const changeMode = () => {
        setMode([...mode, { showing: !showing }]);
    };

    return (
        <RegContext.Provider value={{mode, changeMode}}>
            { props.children }
        </RegContext.Provider>
    );
}

export default RegContextProvider;

我收到了这条消息:

'showing' 未定义 no-undef

谁能帮我解决这个问题?

【问题讨论】:

  • 如果你想要一个道具,为什么还要有一个数组来保存一个对象?
  • @GabrielePetrioli 我是 js 新手,如果方法不正确,您可以更改。

标签: reactjs react-hooks react-context use-state


【解决方案1】:

如果您的所有mode 状态只是保存一个布尔值来显示,您可以将其简化为

const RegContextProvider = (props) => {
    const [showing, setShowing] = useState(false);

    const changeMode = () => {
        setShowing(!showing);
    };

    return (
        <RegContext.Provider value={{showing, changeMode}}>
            { props.children }
        </RegContext.Provider>
    );
}

为了更安全,因为changeMode 依赖于之前的状态,你应该使用回调语法

const changeMode = () => {
    setShowing((showing)=>!showing);
};

https://codesandbox.io/s/bold-darkness-8iscu的演示

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2020-08-01
    • 2021-05-19
    • 2014-03-04
    • 2020-04-13
    相关资源
    最近更新 更多