ReactJs重定向状态变量更改

时间:2016-08-13 16:53:22

标签: javascript reactjs react-router url-redirection

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

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>
    );
}

1 个答案:

答案 0 :(得分:1)

问题出现在这一行:

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

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

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