gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:51:02 24 4
gpt4 key购买 nike

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

如果我想将获取响应放入 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;
});
}

最佳答案

您必须从您的 fetchAPI 函数返回 fetch 请求,并且您还想添加一个额外的 then 并给它一个函数您将 result 置于 toggleButtonState 函数的状态中。

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

示例

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>

关于javascript - React - 单击按钮从外部 API 函数获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53073691/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com