React Js ALT - 在另一个成功时调用函数

React Js ALT - Call function on Success of another

在下面的 Alt Actions 代码中,如何在 addCharacter 成功后调用 getCharacters()?基本上我试图在将新记录保存到数据库后刷新字符列表。

getCharacters() {
    requestPromise('http://localhost:3100/api/characters')
      .then((res) => {
        console.log("Getting Characters");
        var opdata = JSON.parse(res);
        this.actions.getCharactersSuccess(opdata.characters);
      }).catch((err) => {
        console.log('error:', err);
        this.actions.getCharactersFail(err)
      })
  }

  addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
          // How can I recall getCharacters() from here
      }).catch((err) => {
        console.log('error:', err);
      })
  }

商店

getCharactersSuccess(res) {
    this.setState({
      characters: res
    })
  }

您只需调用getCharacters函数即可。您可以通过 this.getCharacters()

addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
         return this.getCharacters();
      }).catch((err) => {
        console.log('error:', err);
      })
  }

这看起来并不 right.It 如果您使用任何架构,如 flux 或 redux,会更好。您可以通过任何方式购买,只需致电 return this.getCharacters();。它指的是 class 中的 getCharacters() 函数。您错过的关键点是 return this. 其中 select 是正确的参考 当您在承诺范围内创建承诺时会发生错误,但您没有t return 来自该 Promise 范围的任何内容。所以 return 将解决您的问题。

addCharacter(data) {
    var options = {
      method: 'POST',
      uri: 'http://localhost:3100/api/characters/add/',
      json: true,
      body: {
        name: data.charName,
        allegiance: data.charAllegiance,
      },
    };
    requestPromise(options)
      .then((res) => {
         return this.getCharacters();
      }).catch((err) => {
        console.log('error:', err);
      })
  }