我无法在动作创建者文件中使用 useHistory 函数 [英] I am not able to use useHistory function in action creator file
问题描述
我正在使用 react-router-dom 和 redux.我在调度后使用 history.push("/") 但它显示错误.我希望用户导航到/"认证成功后(使用GOOGLE)
I am using react-router-dom and and redux. I use history.push("/") after dispatching but it shows error. I want user to navigate to "/" after successfull authentication(USING GOOGLE)
export const googleLogin = () => async (dispatch) => {
try {
const response = await auth.signInWithPopup(provider);
const doc = await db.collection("users").doc(response.user.uid).get();
if (doc.exists) {
await db
.collection("users")
.doc(response.user.uid)
.set(
{
accountDetail: {
emailVerified: response.user.emailVerified,
photoURL: response.user.photoURL,
},
},
{ merge: true }
);
history.push("/")
} else {
await db
.collection("users")
.doc(response.user.uid)
.set({
accountDetail: {
userId: response.user.uid,
displayName: response.user.displayName,
email: response.user.email,
photoURL: auth.currentUser.photoURL,
accountCreatedAt: Date.now(),
},
});
history.push("/")
}
} catch (error) {
await dispatch({ type: AUTH_ERROR, payload: error.message });
}
};
推荐答案
你不能在你的 action creator 文件中使用 useHistory
钩子,因为它既不是 React 函数组件也不是自定义钩子.
You can not use useHistory
hook in your action creator file because it is neither a React function component nor a custom hook.
根据 钩子规则,一个 React Hook,例如useHistory
,只能在函数组件或自定义钩子中使用.
As per rules of hooks, a React Hook, e.g. useHistory
, can only be used in a function component or in a custom hook.
但是,如果您想在 React 组件之外访问 history
对象,您可以创建自己的 history
对象并将其提供给 Router
(来自 react-router-dom)如下图:
But, if you want to access history
object outside a React component, you can create your own history
object and provide it to Router
(from react-router-dom) as shown below:
创建一个文件,history.js:
import { createBrowserHistory } from 'history'
export default createBrowserHistory()
使用 Router
并为其提供您的 history
对象:
Use Router
and provide it your history
object:
import history from '../path/to/history'
import { Router } from 'react-router-dom'
// ...
return (
<Router history={history}>
<App/>
</Router>
)
现在,您可以在动作创建器文件中轻松导入和使用 history
.
Now, you can easily import and use history
in action creator file.
任何js文件:
import history from '../path/to/history'
// ...
history.push("/some/path")
相关:为什么 React-Router-Dom 的 Router 中需要history"?
注意:使用 Router
不会阻止您像使用 useHistory
钩子或 withRouter
HOC 那样使用通常使用即你仍然可以在其他 React 组件中使用钩子或 HOC 来获取 history
.
Note: Using Router
doesn't stop you from using useHistory
hook or withRouter
HOC as you would normally use i.e. you can still use the hook or HOC in other React components to get the history
.
这篇关于我无法在动作创建者文件中使用 useHistory 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!