值不会使用setState(),React嵌套API调用进行更改

时间:2018-06-08 14:06:49

标签: reactjs api

场景非常简单,第一次通话将执行" GET"请求和setState()的结果,第二个调用将" POST"它

Manaje.js

<main class="container">
  <section class="section section--1">Element 1</section>
  <section class="section section--2">Element 2</section>
  <section class="section section--3">Element 3</section>
</main>

Reset.js

export default class Manage extends Component {
    static foo() {
        return adalApiFetch(fetch, 'api/Users/Generate', {
            method: "get",
            headers: { 'Content-Type': 'application/ json' }
        })
            .then(response => response.json())
            .catch(err => console.log(err));
    }

    static update(np, sd) {
        return adalApiFetch(fetch, 'api/Users/Update', {
            method: "post",
            body: JSON.stringify({ np: np, sd: sd }),
            headers: { 'Content-Type': 'application/ json' }
        });
    } }

错误:

export default class Reset extends Component{
    constructor(props) {
        super(props);
        this.state = { test: 'test' };
        this.update = this.update.bind(this);
        this.foo = this.foo.bind(this)
        this.handlefoo = this.handlefoo.bind(this);
    }

foo() {
    Manage.foo()
        .then(data => {
            this.setState({ test: "result_from_foo" });
        });
}

update() {
    var np = this.state.test;

    Manage.Update(np, sd){
      //rest of the code
    }
}
 handlefoo() {
        this.foo();
        this.update();
    }

//=>habldefoo triggered later in the render()
// <div><Button onClick={this.handlefoo} disabled={this.state.selectAll === 0} bsStyle="success">foo</Button></div>

1 个答案:

答案 0 :(得分:0)

我可以看到,您想在update()完成后立即致电foo(),对吧?正如您的代码一样,它会在foo()响应从服务器到达之前调用它们。

您应该使用您在ajax调用中返回的Promise

foo() {
    return Manage.foo() // return the promise that Manage.foo returns
        .then(data => {
            this.setState({ test: "result_from_foo" });
        });
}

update() {
    var np = this.state.test;

    // you have a type error here, it must be update, not Update
    return Manage.update(np, sd).then(()=> { // return the promise that Manage.update returns
      //rest of the code, running after Manage.update returns
    });
}
handlefoo() {
    this.foo().then(() => { // here, call update just after foo completes
        this.update();
    });
}