The 使用历史记录()钩子在我的项目中不起作用。我把它放在不同的组件中,但它们都不起作用。
我正在使用“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>
)
}
- 对于版本
react router dom
少于6.^
您可以使用useHistory()
像你的代码所示的钩子
- 对于最新版本
react router dom
比...更棒6.^
您可以使用useNavigate()
像这样挂钩。无需道具也可使用
import { useNavigate } from 'react-router-dom';
class Login extends Component {
....
let navigate = useNavigate();
navigate('/');
.....
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)