在组件层次结构中,我具有以下代码:
import VisibilityContext from '../visibilityContext';
...
const [showEditModal, setEditModalVisibility] = useState(false);
...
<VisibilityContext.Provider value={{setEditModalVisibility}}>
<EditModal/>
</VisibilityContext.Provider>
在EditModal中,我有这段代码:
import VisibilityContext from '../visibilityContext';
...
const {setEditModalVisibility} = useContext(VisibilityContext);
但是当我在setEditModalVisibility
组件中进行调试时,功能EditModal
为空。如果我通过showEditModal
而不是setEditModalVisibility
,则useContext
为我提供了正确的值。我甚至尝试使用另一个setEditModalVisibility
将useState
置于状态中,并将其传递下来,以防useContext
要求将引用存储在状态中。
我只希望树下的组件能够调用setEditModalVisibility
函数。而且我希望能够共享此功能而不必将它作为道具传递给树。
答案 0 :(得分:1)
这是示例代码,您可以使用Context有效地管理状态。
import React, { createContext, useState, useContext } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const VisibilityContext = createContext();
const Provider = props => {
const [visible, setVisible] = useState(false);
const value = { state: { visible }, actions: { setVisible } };
return (
<VisibilityContext.Provider value={value}>
{props.children}
</VisibilityContext.Provider>
);
};
function App() {
const { state, actions } = useContext(VisibilityContext);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={() => actions.setVisible(!state.visible)}>
{state.visible ? "ON" : "OFF"}
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider>
<App />
</Provider>,
rootElement
);