【发布时间】:2021-05-22 20:46:03
【问题描述】:
我正在尝试从 django 数据库中检索对象(电机)列表并将其存储在我的 MachineTemplate 组件的状态中。
这是组件
export default class MachineTemplate extends Component {
constructor(props) {
super(props);
this.state = {
myName: this.props.match.params.id,
motors: {},
error: "None",
loaded: false
}
this.getMachineDetails = this.getMachineDetails.bind(this);
}
componentDidMount() {
this.getMachineDetails();
}
getMachineDetails = () => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: this.state.myName,
}),
};
fetch("http://127.0.0.1:8000/get-motors", requestOptions)
.then((response) => {
if (response.ok) {
this.setState({ motors: response.data });
} else {
this.setState({ error: "Motors not found." });
}
})
.catch((error) => {
console.log(error);
});
this.setState({loaded: true});
}
render() {
if (this.state.loaded) {
return (
<div>
<h1>{this.state.name}</h1>
<h3>{this.state.error}</h3>
{this.state.motors.map(motor => {
return <Button key = {motor.number}>{motor.number}</Button>
})}
</div>
)
} else {
return(
<div>
<h1>Awaiting machine details...</h1>
</div>
)
}
}
}
这是我得到的错误
TypeError: Cannot read property 'map' of undefined
我可以确认 fetch 正确返回了我需要的电机对象列表,这些对象在响应中的格式如下:
0: {number: 0, enabled: true, item: "EMPTY", machine: 48}
我能够通过不同组件中的简单名称列表使这个精确的设置正常工作,因此我们将不胜感激。
【问题讨论】:
-
嗨@SpencerBrereton 欢迎!使用
fetch时,您需要先使用response.json()提取数据。 developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch