Предполагая, что у вас неприятный контекст ShipmentsContext
, вы случайно пропускаете соответствующий ShipmentsContext.Provider
?
Вы сбрасываете <ShipmentsContext.Consumer>
и сохраняете <ShipmentsContext.Provider>
. Потребитель контекста может быть установлен с помощью contextType
в качестве поля статического класса:
class MyComp extends React.Component {
static contextType = ShipmentsContext;
...
}
// When you don't want to/cannot use public class
// fields syntax, this is the alternative:
// MyComp.contextType = ShipmentsContext;
Вот простой пример теста:
const ShipmentsContext = React.createContext({
isDetailsVisible: "false from default"
});
class MyComp extends React.Component {
static contextType = ShipmentsContext;
render() {
return this.renderHeader();
}
renderHeader() {
return <p>{JSON.stringify(this.context)}</p>;
}
}
const App = () => {
// state realized with React Hooks. You could also use a
// class component and `setState` for App
const [contextValue, setContextValue] = React.useState({
isDetailsVisible: "true from Provider"
});
return (
<ShipmentsContext.Provider value={contextValue}>
<button
onClick={() =>
setContextValue({ isDetailsVisible: "UPDATED true from Provider" })
}
>
Update Context
</button>
<MyComp />
</ShipmentsContext.Provider>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.1/umd/react.production.min.js" integrity="sha256-vMEjoeSlzpWvres5mDlxmSKxx6jAmDNY4zCt712YCI0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.1/umd/react-dom.production.min.js" integrity="sha256-QQt6MpTdAD0DiPLhqhzVyPs1flIdstR4/R7x4GqCvZ4=" crossorigin="anonymous"></script>
<div id="root"></div>
При нажатии на кнопку «Обновить контекст» контексту будет предоставлено новое значение, и renderHeader
также получит уведомление об изменении.
Дайте мне знать, если это соответствует вашему делу. Удачи!