我试图在单击“信息”按钮时显示每个字符的数据。我知道这是因为在onButtonClickHandler
函数中它看不到状态。我也尝试过,this.state.person
但它给了我一个错误,说“无法读取状态”。如果我尝试,state.person
它会给我“未定义”。
最好的方法是什么?谢谢
import React from "react";
export default class FetchActors extends React.Component {
state = {
loading: true,
person: null
};
async componentDidMount() {
const url = "https://swapi.dev/api/people/";
const response = await fetch(url);
const data = await response.json();
this.setState({ person: data.results, loading: false });
}
render() {
if (this.state.loading) {
return <div>loading...</div>;
}
if (!this.state.person.length) {
return <div>didn't get a person</div>;
}
function onButtonClickHandler(state) {
console.log(state.person);
};
return (
<div>
<h1>Actors</h1>
{this.state.person.map(person =>(
<div>
<div>
{person.name}
<button onClick={onButtonClickHandler}>Info</button>
</div>
</div>
))}
<button onClick={onButtonClickHandler}>Enter</button>
</div>
);
}
}
慕哥9229398
MMTTMM
料青山看我应如是
千万里不及你
相关分类