I wrote a Login
component which contains the hook useEffect
that must access to the history
object of the component:
export default (props: { children: React.ReactNode }) => {
const alertContext = useContext(AlertContext);
const authContext = useContext(AuthContext);
const { setAlert } = alertContext;
const { login, error, clearErrors, isAuthenticated } = authContext;
useEffect(() => {
if (isAuthenticated) {
props.history.push('/');
}
if (error === 'Invalid Credentials') {
setAlert(error, 'danger');
clearErrors();
}
// es-lint-disable-next-line
}, [error, isAuthenticated, props.history]);
even though I've defined React.ReactNode
as props
type for the component, I get:
Property 'history' does not exist on type '{ children: ReactNode; }'
This error happen on this line:
props.history.push('/');
How can I fix that?
Based on your component which is functional component, you can use useHistory()
hook instead:
React Router ships with a few hooks that let you access the state of the router and perform navigation from inside your components.
The
useHistory
hook gives you access to the history instance that you may use to navigate.
You can import it as:
import { useHistory } from "react-router-dom";
So try as the following:
export default (props: { children: React.ReactNode }) => {
const history = useHistory()
// rest of the code
}
Then use without props
as:
history.push('/');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.