thi*_*ilg 5 websocket reactjs react-native react-context
我只是好奇是否可以在 Context API 中使用 Context API。例如,我将为 AppState 提供一个 Context API,并希望在另一个处理 WebSocket 连接的 Context API 中使用它?
受到 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)
这是使用钩子而不是上下文的好场景。
// 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)
| 归档时间: |
|
| 查看次数: |
5055 次 |
| 最近记录: |