有一个包含对象数组的端点,每个对象都是一个“todo”对象,具有“title”和 bool 值“checked”。我正在尝试将它们放在页面中。
我有以下 react 组件,我已经运行并且工作正常:
class TodosPage extends React.Component {
render() {
return (
<div>
<AddToDo></AddToDo>
<br></br>
<Row text11="Run" isChecked={true}></Row>
</div>
)
}
}
每一行代表一个“待办事项”,您可以看到一个属性是“text11”,另一个是 bool 值“isChecked”。
我正在尝试从端点读取数据,遍历待办事项并根据我读取的数据创建新的 < Row > 组件。
我有这段代码,它从端点读取并打印我正在寻找的那些值(我在 playui.io 上测试过,它们有效:
function getAll() {
fetch("https://.....", {
method: "GET",
headers: headers
})
.then(function(response){
return response.json();
})
.then(function(data){
for (var i = 0; i < data.length; i++) {
console.log(data[i]["title"])
console.log(data[i]["checked"])
}
});
}
基本上我试图将这两段代码放在一起,这就是我遇到的困难。有没有一种直接的方法可以实现这一目标?
最佳答案
您需要在 componentDidMount()
中加载您的数据,并将其保存到您的组件 state
。然后您可以在该数据在 View 中可用时使用该数据。
注意:对于更高级的模式,您需要在尝试在渲染中引用它之前检查状态变量是否存在,否则您将得到引用错误。
class TodosPage extends React.Component {
//setup state on your component. you can also do this in a constructor if you like
state = {
data:[]
}
// constructor(props){
// super(props);
// this.state= {
// data:[]
// }
// }
componentDidMount(){
//load your data when the component mounts
fetch("https://.....", {
method: "GET",
headers: headers
})
.then(res=>res.json()).then(data=>{
//add the data to component state
this.setState({data});
});
}
render() {
//when data loads, your component will render the rows of the data using array.map()
return (
<div>
<AddToDo></AddToDo>
<br></br>
{this.state.data.map((row,i)=><Row text11="">{row.title}</Row>)}
</div>
)
}
}
请查阅 google 和 react 文档以获取其他此类信息。很明显你缺乏对 react 的理解,但是这些基本的知识是现成的。
关于javascript - 尝试从端点读取数据并使用该数据创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58866125/