ReactJs在状态变量改变时重定向

ReactJs Redirect on state variable change

本文关键字:重定向 改变 变量 状态 ReactJs      更新时间:2023-09-26

我试图通过ajax获得json,如果我的响应变量是可接受的使用react路由器重定向。我怎样才能做到呢?

successRedirect(){
    if (this.responseCode.equals("what I need")) {
        router.transitionTo('/')
    }
}
createCheckout() {
    $.ajax({
        url: "someurl",
        dataType: 'json',
        type: 'POST',
        cache: false,
        data: this.data,
        success: function(response) {
            this.setState({
                response: response,
                responseCode: response.result.code
            });
        }.bind(this),
            error: function(xhr, status, err) {
                console.error(this.props.url, status, err.toString());
        }.bind(this)
    })
}

函数必须在获得响应后调用。例如,我有这个代码,并在渲染响应采取并显示一段时间后:

render(){
    return (
        <div>
            <div>Response - {this.state.responseCode}</div>
        </div>
    );
}

问题似乎出在这一行:

if (this.responseCode.equals("what I need")) {

通过this.setState添加的项在this.state对象上可用。此外,JavaScript不提供equals函数,但您可以与===进行比较

if (this.state.responseCode === "what I need") {