尝试从端点读取数据并使用该数据创建组件

有一个端点,该端点具有对象数组,每个对象都是一个“待办事项”对象,该对象具有一个“标题”和一个布尔值“已选中”。我正在尝试将其放在页面中。

我有以下已经运行且可以正常运行的react组件:

class TodosPage extends React.Component {

    render() {
        return (
            <div>
                <AddToDo></AddToDo>
                <br></br>
                <Row text11="Run" isChecked={true}></Row>

            </div>
        )
    }
}

每行代表一个“要做”,您可以看到一个道具是“ text11”,另一个道具是布尔值“ isChecked”。

我正在尝试从端点读取,遍历待办事项并根据读取的数据创建新的组件。

我有这段代码从端点读取并打印出我正在寻找的值(我在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"])
    }


  });

}

基本上,我试图将这两段代码放在一起,而这正是我遇到的困难。有没有直接的方法可以实现这一目标?

beichenx 回答:尝试从端点读取数据并使用该数据创建组件

您需要将数据加载到componentDidMount()中,并将其保存到组件state中。那么您就可以在视图中使用该数据了。

注意:对于更高级的模式,您需要先检查状态变量,然后再尝试在渲染中引用它,否则会出现引用错误。

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文档。很明显,您缺乏对反应的理解,但是对这些基本知识的了解是很容易获得的。

本文链接:https://www.f2er.com/3099492.html

大家都在问