【发布时间】:2021-10-07 07:56:30
【问题描述】:
useHistory() 钩子在我的项目中不起作用。我在不同的组件中有它,但它们都不起作用。 我正在使用“react-router-dom”:“^5.2.0”,
import {useHistory} from 'react-router-dom'
const history = useHistory()
const logout = () => {
toggleMenu()
setUser(null)
dispatch({type: 'LOGOUT'})
history.push('/')
}
而且在行动中它也不起作用
export const signin = (formdata, history, setError) => async (dispatch) => {
try {
const {data} = await API.signIn(formdata)
if(data.error){
setError(data.message)
}else{
dispatch({type: SIGNIN, data})
history.push('/dashboard')
}
} catch (error) {
setError(error)
console.log(error)
}
}
这是我的 router.js 文件
const Router = () => {
const user = JSON.parse(localStorage.getItem('profile'))
return (
<BrowserRouter>
<>
{user && <Navigation/>}
<Switch>
<Route path='/page-not-found' component={Auth}/>
<Route path='/' exact component={()=>((user && user.result) ? <Redirect to="/dasboard"/> : <Auth/>)} />
<Route path='/dashboard' component={() => (user ? <Dashboard/> : <Redirect to='/'/>)} />
<Route path='/books-purchase' component={() => (user ? <BooksPage/> : <Redirect to='/' />)} />
</Switch>
</>
</BrowserRouter>
)
}
【问题讨论】:
-
“不工作”是什么意思?是不是出错了?什么都没有发生?
-
什么都没有发生
-
dispatch 和 state set 怎么样,他们工作了吗?
-
是的,除了 history.push() 之外一切正常
-
那么我们需要查看更多代码。你能分享你在哪里初始化你的路由和调用history.push的其余组件吗?
标签: reactjs react-router-dom redux-thunk