【问题标题】:React Js ALT - Call function on Success of anotherReact Js ALT - 在另一个成功时调用函数
【发布时间】:2017-08-28 00:57:17
【问题描述】:

在下面的 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
    })
  }

【问题讨论】:

标签: mongodb reactjs mongoose alt


【解决方案1】:

这看起来不对。如果您使用任何架构,例如flux或redux,那就更好了。您可以通过任何方式购买,只需致电return this.getCharacters();。它指的是你的类中的 getCharacters() 函数。您错过的关键点是 return this. 选择正确的引用当您在 Promise 范围内创建 Promise 时会发生错误,但您不会从该 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);
      })
  }

【讨论】:

  • 我正在使用 AltJs。我已经尝试过这个解决方案,但收到错误:在处理程序中创建了一个承诺,但没有从它返回
  • 尝试在this.getCharacters()前面加一个return关键字;
  • 嗯,这消除了警告,但是 getCharacters 的响应被返回为未定义。
  • hmm 这可能是由 js 的 asycn 特性引起的尝试类似 this.getCharacters();返回 "";
  • 没有运气仍然是同样的错误,这很奇怪,因为我正在控制台记录 opData 并且它按预期返回直到 getCharactersSuccess()
【解决方案2】:

您只需要调用 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);
      })
  }

【讨论】:

  • 我试过这个但收到错误:在处理程序中创建了一个承诺,但没有从它返回
  • 您会收到警告,而不是错误。你只需要添加return this.getCharacters()
猜你喜欢
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多