Reactjs React-api调用后重定向不起作用
我正在尝试从Reactjs React-api调用后重定向不起作用,reactjs,Reactjs,我正在尝试从react router dom使用重定向 因此,在发出API post请求后,如果成功,我想返回主页 有什么想法吗?以下有什么问题吗 try { const resp = await axios.post('http://localhost:8080/add', page); if (resp.status == 200) { return <Redirect to="/" /> } } c
react router dom
使用重定向
因此,在发出API post请求后,如果成功,我想返回主页
有什么想法吗?以下有什么问题吗
try {
const resp = await axios.post('http://localhost:8080/add', page);
if (resp.status == 200) {
return <Redirect to="/" />
}
} catch (err) {
console.log(err);
}
当我收到错误时:error:Invariant失败:您不应该在
谢谢。您可能需要使用
setState
来更改状态,并在渲染中重定向
class MyComponent extends React.Component {
state = {
redirect: false
}
async foo () {
try {
const resp = await axios.post('http://localhost:8080/add', page);
if (resp.status == 200) {
this.setState({redirect:true})
}
} catch (err) {
console.log(err);
}
}
render () {
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/'/>;
}
...
}
类MyComponent扩展了React.Component{
状态={
重定向:false
}
异步foo(){
试一试{
const resp=等待axios.post('http://localhost:8080/add,第页);
如果(各自状态==200){
this.setState({redirect:true})
}
}捕捉(错误){
控制台日志(err);
}
}
渲染(){
const{redirect}=this.state;
如果(重定向){
返回;
}
...
}
或者,您可以尝试使用历史记录
谢谢-是的,我读过类似的内容,但我仍然收到一个错误-我更新了我的问题..我希望路由器
包含了您的组件,它是-但是我现在看到错误无法读取未定义的属性
的“位置”,然后是警告:失败的属性类型:道具
history`在Router
中按要求标记,但其值是未定义的
`啊-它必须是浏览器路由器
所以
谢谢你的帮助。很好,干杯,伙计:D
class MyComponent extends React.Component {
state = {
redirect: false
}
async foo () {
try {
const resp = await axios.post('http://localhost:8080/add', page);
if (resp.status == 200) {
this.setState({redirect:true})
}
} catch (err) {
console.log(err);
}
}
render () {
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/'/>;
}
...
}