React Router 根据组件的 API 调用有条件地导航到不同的页面



使用React Router,我想根据API调用的结果有条件地导航到三个页面中的一个,但我很难弄清楚如何做到这一点。

我曾尝试返回带有if/else中路由的ConditionalLink,并用它来包装按钮,而不是JSX中的Link,但这似乎不起作用(可能是因为在提交表单/单击下一个按钮时JSX已经呈现了?(。

我在路由器本身中看到了许多其他问题/答案,但这个API调用和随后的决策发生在单个组件中。

EDIT:我不能使用钩子,因为这是一个基于类的组件,并且由于其他约束而必须保留它。

API调用的基本逻辑代码:

onSubmit = (event) => {
setByValue('showLoadingSpinner', true);
api.dataLookup(query)
.then(data => {
setByValue('showLoadingSpinner', false)
saveDetails(data)
if (data.isValid) {
// Navigate to first page
} else {
// Navigate to second page
}
})
.catch(error => {
setByValue('showLoadingSpinner', false)
console.log(error)
// Navigate to third page
})
}
}

JSX("nextButton"嵌套在一个调用onSubmit的表单中(:

<div className={classes.button}>
<Link to="/nextpage">
<NextButton text="Next"/>
</Link>
</div>

您只需要使用useHistory挂钩来获取history对象,然后您就可以使用history.push(someUrl)从AJAX回调中将用户发送到您想要的任何位置。

const history = useHistory();
return (<div className={classes.button}>
<Link to="/nextpage">
<NextButton text="Next" history={history}/>
// ...

onSubmit = (event) => {
setByValue('showLoadingSpinner', true);
api.dataLookup(query)
.then(data => {
setByValue('showLoadingSpinner', false)
saveDetails(data)
if (data.isValid) {
history.push('/foo');

有关更多详细信息,请参阅:https://reacttraining.com/react-router/web/api/Hooks/usehistory

最新更新