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

Dog*_*oge 6 javascript asynchronous fetch reactjs

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

如果我想将 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;
    });
 }
Run Code Online (Sandbox Code Playgroud)

Tho*_*lle 9

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

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

例子

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"));
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)