我正在使用 ReactJS
并且有一个表单(组件),如果发布请求成功,则需要重定向到另一个组件。我刚刚开始使用 react 路由器,所以这就是我尝试重定向的方式。
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Redirect, Link } from 'react-router-dom';
import NextComponent from '/NextComponent';
import axios from 'axios';
class CurrentComponent extends Component {
constructor() {
super();
this.state = {
value: ''
redirect: false
};
}
handleSubmit() {
axios.post('xxx/yyy', {
xxx: yyy
})
.then(function() {
console.log('Success');
this.setState({redirect: true});
})
.catch(function() {
console.log('Error');
});
}
render() {
return(
<div>
<form>
<div className="form-group">
<input type="name" placeholder="name" />
</div>
<div className="form-group">
<button type="button" onClick={this.handleSubmit.bind(this)} >Submit</button>
{this.state.redirect &&
<Redirect to={{
pathname: '/nextcomponent',
state: {from: this.state.value}
}} />
}
</div>
<Router>
<Route path="/nextcomponent" component={NextComponent} />
</Router>
</form>
</div>
);
}
}
export default PresentComponent;
它不是重定向,我一直在试图解决这个问题。我确信有更好的解决方案可用,但由于我缺乏知识,我不确定是否实现它。任何帮助表示赞赏。谢谢。
最佳答案
您可能在调用后没有获得state
,请尝试将handleSubmit
方法修改为:
handleSubmit() {
let _this = this;
axios.post('xxx/yyy', {
xxx: yyy
})
.then(function() {
console.log('Success');
_this.setState({redirect: true});
})
.catch(function() {
console.log('Error');
});
}
根据新代码更新:
class ComponentOne extends Component {
constructor() {
super();
this.UpdateRoute= this.UpdateRoute.bind(this);
this.state = {
value: ''
};
this.loggedin = false;
}
const UpdateRoute = () => (
<Router>
<Route exact path="/xyz" render={() => (
loggedin ? (
<ComponentTwo />
) : (
<ComponentOne />
)
)}/>
</Router>
)
handleSubmit() {
let _this = this;
axios.post('/xyz', {
xxx: yyy,
})
.then(function(response) {
_this.loggedin = true;
_this.UpdateRoute();
})
.catch(function() {
console.log('Error');
});
}
render() {
return(
<div>
<h1>Load First</h1>
<button type="button" onClick={this.handleSubmit.bind(this)}>Submit</button>
</div>
);
}
}
export default ComponentOne;
关于javascript - 使用 react 路由器重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44118263/