javascript React - 单击按钮从外部 API 函数中获取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53073691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:07:09  来源:igfitidea点击:

React - Fetch from external API function on button click

javascriptreactjsasynchronousfetch

提问by Doge

I'm trying to start an API call from a component when a user clicks a button. One URL param depends on the word a user selected before clicking the button. The fetch function is in an external function. When I call the function on button click and console log the result, it shows undefined, probably because of the async nature of the function.

当用户单击按钮时,我试图从组件启动 API 调用。一个 URL 参数取决于用户在单击按钮之前选择的词。fetch 函数在一个外部函数中。当我在按钮单击时调用该函数并控制台记录结果时,它显示undefined,可能是因为该函数的异步性质。

How can I solve this if I want to put the fetch response into the Appcomponent state?

如果我想将 fetch 响应放入App组件状态,我该如何解决这个问题?

import { fetchAPI } from '../fetchAPI';

export default class App extends Component {

constructor() {
    super();
    this.toggleButtonState = this.toggleButtonState.bind(this);
    state = { ... }
}

toggleButtonState() {
    let selectedWord = window.getSelection().toString();
    fetchAPI(selectedWord);
    // call the fetchAPI function and put the result into state
}

export function fetchAPI(param) {
    // param is a highlighted word from the user before it clicked the button
    fetch('https://api.com/?param=' + param)
    .then(function(result) {
        return result;
    });
 }

回答by Tholle

You have to return the fetchrequest from your fetchAPIfunction, and you also want to add an additional thenand give it a function in which you put the resultin the state in the toggleButtonStatefunction.

你必须fetch从你的fetchAPI函数返回请求,你还想添加一个额外的then并给它一个函数,在这个函数中你将 放入函数result中的状态toggleButtonState

In your example the theninside the fetchAPIfunction is redundant, since it just returns the value as is. You can remove that and still get the same result.

在您的示例中thenfetchAPI函数内部是多余的,因为它只是按原样返回值。您可以删除它并仍然获得相同的结果。

Example

例子

function fetch() {
  return new Promise(resolve => setTimeout(() => resolve(42), 1000));
}

function fetchAPI(param) {
  // param is a highlighted word from the user before it clicked the button
  return fetch("https://api.com/?param=" + param);
}

class App extends React.Component {
  state = { result: null };

  toggleButtonState = () => {
    let selectedWord = window.getSelection().toString();
    fetchAPI(selectedWord).then(result => {
      this.setState({ result });
    });
  };

  render() {
    return (
      <div>
        <button onClick={this.toggleButtonState}> Click me </button>
        <div>{this.state.result}</div>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

回答by Aditya

toggleButtonState() {
  let selectedWord = window.getSelection().toString();
  fetchAPI(selectedWord).then(result => this.setState({result});
}

export function fetchAPI(param) {

  // param is a highlighted word from the user before it clicked the button
  return fetch('https://api.com/?param=' + param)
}

This will solve your problem. If you don't want to change the fetch API like that just add 'return' before calling fetch as shown below.

这将解决您的问题。如果您不想像这样更改 fetch API,只需在调用 fetch 之前添加“return”,如下所示。

toggleButtonState() {
  let selectedWord = window.getSelection().toString();
  fetchAPI(selectedWord).then(result => this.setState({result});
}

export function fetchAPI(param) {
  return fetch('https://api.com/?param=' + param)
    .then(function(result){
      return result;
    });
}

回答by Code-Apprentice

One solution is to provide a callback to your fetchAPI()function:

一种解决方案是为您的fetchAPI()函数提供回调:

function fetchAPI(param, callback) {
  // param is a highlighted word from the user before it clicked the button
  return fetch("https://api.com/?param=" + param)
    .then(callback);
}

You can call the modified function like this:

您可以像这样调用修改后的函数:

fetchAPI(selectedWord, result =>
  this.setState({ result });
);

Note that this follows the same general principle as the other answers. You need to call setState()with the correct thisreference. You can only do so from a function inside your component class.

请注意,这遵循与其他答案相同的一般原则。您需要setState()使用正确的this参考来调用。您只能通过组件类中的函数执行此操作。