【发布时间】:2022-01-14 20:53:52
【问题描述】:
我需要从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;
【问题讨论】:
-
您没有
Animal组件。您的App组件上有一个Animal方法。使用自己的方法创建一个新组件(或使用钩子创建一个新的功能组件)。
标签: javascript reactjs