Cip*_*ian 6 javascript reactjs react-native
新的 React Context API 很棒,但是我似乎总是在 React 组件之外访问它。或者从上下文中重置一个值(例如由于在 fetch 函数中发生的异步操作)没有简单的方法来做到这一点..
那么,有没有办法在 React 组件之外访问 React Context Consumer 中的值?
后期编辑:我继承了一个基于 Redux 的项目并慢慢过渡到它。在动作创建者中,我有一个注销功能,可以清除商店的内容:
export const logoutRequest = () => dispatch => {
navigate('Welcome')
// Reset apollo data
client.resetStore()
persistor.purge()
// Reset context api data HERE
//
}
Run Code Online (Sandbox Code Playgroud)
我可以轻松地在调用注销请求的组件中创建一个使用者,但这发生在 3 个不同的组件中,我不想在那里复制代码..
小智 5
您最终会调用logoutRequest()一个组件,对吗?如果您不想重复代码,您可以创建一个自定义挂钩:
const useLogout = () => {
const resetContext = React.useContext(SomeContext);
const logoutRequest = () => dispatch => {
navigate('Welcome');
client.resetStore();
persistor.purge();
resetContext();
};
return logoutRequest;
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以调用const logoutRequest = useLogout()你的组件了。您也可以对异步操作执行类似的操作。
不,你不能。更新上下文的唯一方法是更改发送到 Context.Provider 的值。
对于异步操作,通常会将结果保存在根组件(或呈现提供程序的组件)中并更改发送的值。或者您可以在上下文中创建一个函数,如下所示https://reactjs.org/docs/context.html#updating-context-from-a-nested-component
| 归档时间: |
|
| 查看次数: |
6584 次 |
| 最近记录: |