[英]React - Fetch from external API function on button click
I'm trying to start an API call from a component when a user clicks a button. 当用户单击按钮时,我试图从组件开始API调用。 One URL param depends on the word a user selected before clicking the button.
一个URL参数取决于用户在单击按钮之前选择的单词。 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. 当我单击按钮并在控制台上记录结果时,该结果显示为
undefined
,这可能是由于该函数的异步性质。
How can I solve this if I want to put the fetch response into the App
component state? 如果要将提取响应置于
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;
});
}
You have to return the fetch
request from your fetchAPI
function, and you also want to add an additional then
and give it a function in which you put the result
in the state in the toggleButtonState
function. 您必须从
fetchAPI
函数返回fetch
请求,并且还想要添加一个附加请求, then
为其提供一个函数,在其中将result
放入toggleButtonState
函数的状态中。
In your example the then
inside the fetchAPI
function is redundant, since it just returns the value as is. 在您的例子中,
then
里面的fetchAPI
功能是多余的,因为它只是返回的值是。 You can remove that and still get the same result. 您可以删除它,但仍然得到相同的结果。
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>
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;
});
}
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 this
reference. 您需要使用正确的
this
引用来调用setState()
。 You can only do so from a function inside your component class. 您只能从组件类内部的函数中进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.