[英]how do i import and use promise function on my react component?
[英]how do I use "this" on an component function in react?
我需要從Animal
組件調用this.getFact
,但是使用this
會引發TypeError: this is undefined
import './App.css';
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fact: '',
}
}
getFact(endpoint) {
fetch(endpoint)
.then(response => response.json())
.then(data => {
this.setState({
fact: data.text,
});
})
}
Animal(props) {
return (
<div>
<h1>{props.name}</h1>
<button onClick={() => this.getFact(props.endpoint)}>get a {props.name.toLowerCase()} fact</button>
</div>
)
}
render() {
return (
<div className="App">
<div>
<p>{this.state.fact}</p>
</div>
<div className="animals">
<this.Animal name="Dog" endpoint="https://some-random-api.ml/facts/dog" />
<this.Animal name="Cat" endpoint="https://some-random-api.ml/facts/dog" />
<this.Animal name="Bird" endpoint="https://some-random-api.ml/facts/dog" />
<this.Animal name="Otter" endpoint="https://some-random-api.ml/facts/dog" />
</div>
</div>
);
}
}
export default App;
您需要綁定兩個函數(getFact 和 Animal)才能在 Animal function 中使用它。 在您的構造函數中執行以下操作:
constructor(props) {
super(props);
this.state = {
fact: ""
};
// Here you will bind the functions so they can be callable with this
this.getFact = this.getFact.bind(this);
this.Animal = this.Animal.bind(this);
}
這將解決問題,但我建議將 Animal 組件移到 class 之外,並將 getFact 作為道具傳遞。 您仍然需要綁定 getFact function,但老實說,它會更加反應,並且從長遠來看更易於維護。 像這樣的東西
function Animal(props) {
return (
<div>
<h1>{props.name}</h1>
<button onClick={() => props.getFact(props.endpoint)}>
get a {props.name.toLowerCase()} fact
</button>
</div>
);
}
class AppReactWay extends React.Component {
constructor(props) {
super(props);
this.state = {
fact: ""
};
this.getFact = this.getFact.bind(this);
}
// Same code as you have
render() {
return (
<div className="App">
<div>
<p>{this.state.fact}</p>
</div>
<div className="animals">
<Animal
name="Dog"
getFact={this.getFact}
endpoint="https://some-random-api.ml/facts/dog"
/>
</div>
</div>
);
}
}
export default App;
同樣在檢查 API 響應后,您需要修改 getFact function,不是 data.text,而是 data.fact。
getFact(endpoint) {
fetch(endpoint)
.then((response) => response.json())
.then(({ fact }) => {
this.setState({
fact
});
});
}
這是一個包含兩個示例的工作沙箱。
更好的方法是直接為每只動物調用{this.Animal({ name: 'Dog', endpoint: 'https://some-random-api.ml/facts/dog'})}
等等。
最好的方法是讓Animal
擁有它自己的組件並將getFact
function 作為參數傳遞,不要忘記在這種情況下你需要綁定它,否則它會失去這個上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.