1

如何将状态从 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

谁能帮我解决这个问题??

4

1 回答 1

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

于 2020-03-24T12:24:39.037 回答