[英]I am unable to render components dynamically in react.js,
因此,当我尝试从在线 JSON 文件将组件动态渲染到视图中时,我开始使用 react 并卡住了。 我正在使用 axios.get 从 JSON 获取信息,但无法正确呈现它。
任何帮助都非常感谢!!
Json :项目中使用的Json Link
import React, { Component } from "react";
import axios from "axios";
class Lessons extends Component {
state = {
Questions: []
};
async componentDidMount() {
const { data: Questions } = await axios.get(
"https://api.myjson.com/bins/1axyok"
);
this.setState({ Questions });
console.log(Questions);
console.log(this.state.Questions.QuestionID);
}
render() {
return (
<h4 style={{ padding: "20px" }}>{this.state.Questions.QuestionID}</h4>
);
}
}
this.state.Questions.QuestionID(一个例子)的值没有被渲染到视图中
它应该呈现的部分(在问题下方) QuestionID 是此处项目的空白检查屏幕截图
所以我尝试在控制台中创建两个日志(检查代码)并得到以下输出。 对象的 console.log => console.log(Questions) 给出了结果。 另一个,在此处显示console.log 的未定义检查图像
Questions
是一个包含一个元素的数组,因此您希望在尝试访问QuestionId
之前获取数组的元素0
。 Questions
也是 response 对象的一个属性,因此您需要使用它而不仅仅是data
。
例子
class Lessons extends Component {
state = {
Questions: []
};
async componentDidMount() {
const { data } = await axios.get(
"https://api.myjson.com/bins/1axyok"
);
this.setState({ Questions: data.Questions });
}
render() {
return (
<h4 style={{ padding: "20px" }}>
{this.state.Questions[0] && this.state.Questions[0].QuestionID}
</h4>
);
}
}
这是因为 axios 的response.data
包含原始 JSON 数据。 现在使用您发布的 JSON,该对象包含一个 Array Question
并且该 Array 中的每个项目都包含QuestionID
。 所以将组件代码修改成这样
class Lessons extends Component {
state = {
Questions: []
};
async componentDidMount() {
const { data: Questions } = await axios.get(
"https://api.myjson.com/bins/1axyok"
);
this.setState({ Questions: Questions.Questions }, () => {
console.log(this.state.Questions);
});
}
render() {
return this.state.Questions.map((each) => (
<h4 style={{ padding: "20px" }}>
{each.QuestionID}
</h4>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.