kri*_*tiz 3 routes reactjs react-hooks
我正在努力实现这个目标
import {isAuthorized} from '../somewhere'
async componentDidMount() {
const authorized = await isAuthorized()
if(!authorized){
this.props.history.push('/login')
}
}
Run Code Online (Sandbox Code Playgroud)
在反应钩子中,我怎样才能实现这个确切的功能,谢谢
您可以使用useHistoryhook 来访问history实例并调用history.pusha 内部useEffect来导航到所需的路线。
import {isAuthorized} from '../somewhere';
import { useHistory } from "react-router-dom";
function SomeComponent(props) {
const history = useHistory()
useEffect(() => {
const navigate = async () => {
const authorized = await isAuthorized();
if(!authorized){
history.push('/login')
}
}
// call the async function
navigate()
}, [])
}
Run Code Online (Sandbox Code Playgroud)
请记住,由于可能存在竞争条件,React 不允许回调为useEffect函数。async因此,您必须在钩子async内定义一个新函数useEffect并调用它。
| 归档时间: |
|
| 查看次数: |
7621 次 |
| 最近记录: |