reactjs - axios调用成功响应后如何重定向
问题描述
我正在拨打 axios 电话,在成功请求后我想请求另一个网页。所以我喜欢
getShow = event =>{
event.preventDefault();
const headers = {
'Content-type': 'application/json',
Authorization: 'Client ' + localStorage.getItem('secretKey')
};
axios
.get('/api/getshow', {
headers: headers,
params: {
name: this.state.sendername,
email:this.state.senderemail
}
})
.then(res => {
console.log(res.data.name);
return <Redirect to='/show?name=res.data.name'/>
});
};
但这不是重定向。我也尝试删除 event.preventDefault(); 但没有用。感谢任何帮助。
解决方案
创建一个称为重定向的状态:
constructor(props) {
super(props);
this.state = { redirect: null }
}
或者用钩子:
const [ redirect, setRedirect ] = useState(null);
您需要在渲染中设置组件:
if (redirect) {
return <Redirect to={redirect} />
}
然后在你的 axios 的那个 .then 中,只需将重定向设置为你想要重定向的路由:
axios
.get('/api/getshow', {
headers: headers,
params: {
name: this.state.sendername,
email:this.state.senderemail
}
})
.then(res => {
console.log(res.data.name);
//Hooks
setRedirect(`/show?${res.data.name}`)
// No hooks
this.setState({ redirect: `/show?${res.data.name}` });
});
推荐阅读
- css - Bootstrap 4 50% 高的行/列
- highcharts - Highcharts CSV 导出,日期不正确
- scripting - 如何在 pl/pgsql 中编写脚本而不是函数?
- excel - Excel VBA 进入每个工作表中的单元格并刷新(F2+Enter)
- docker - 打包预配置的 solace docker 镜像的推荐方法是什么
- javascript - 如何计算给定时间之前的小时数
- python-3.x - 我正在尝试将字典列表中的数据导出到数据框中,但我不断收到此错误:标量变量的索引无效
- swift - 如何使用 swift 修复 JSON-RPC 错误代码 591
- php - 如何在 Elastic Search 中进行多重排序
- javascript - 手风琴的 CSS 过渡动画顺序问题