我可以在 Context API 中使用 React Context API 还是必须合并它们?

thi*_*ilg 5 websocket reactjs react-native react-context

我只是好奇是否可以在 Context API 中使用 Context API。例如,我将为 AppState 提供一个 Context API,并希望在另一个处理 WebSocket 连接的 Context API 中使用它?

thi*_*ilg 6

受到 Joseph 答案的启发,我正在考虑在自定义挂钩中一起使用这两个上下文 api。

useMultipleContexts(){
  const contextOne = useContext(ContextOne);
  const contextTwo = useContext(ContextTwo);

  /**
   * Do something with both contexts
   * in a custom hook that can be used
   * multiple times with the same state
   */


}

Run Code Online (Sandbox Code Playgroud)


Jos*_* D. 5

这是使用钩子而不是上下文的好场景。

// custom hook
function useAppState() {
  //add handlers here

  return appState;
}

function WebSocket() {
  const appState = useAppState();

  // do something (i.e reconnect) every time appState changes
  useEffect(() => { /* do something */, [appState])
}

function App() {
  return <WebSocket />
}
Run Code Online (Sandbox Code Playgroud)