简体   繁体   English

如何从 reactjs 中的回调函数渲染数据?

[英]How do I render data from a callback function in reactjs?

I making requests to my Django backend, the data is a list of information.我向我的 Django 后端发出请求,数据是一个信息列表。 What I need to do is is render a piece of HTML for each item in the list, this list is retrieved asynchronously.我需要做的是为列表中的每个项目渲染一段 HTML,这个列表是异步检索的。 However in the render() where I'm returning some HTML I can't place that in a asynchronous function.但是,在我返回一些 HTML 的render() ,我无法将其放在异步函数中。 I've never had to use this with react:我从来没有必要在反应中使用它:

var allLeads = []
// get a list of all the leads from the Django backend 
 const getAllLeads =  (callback) => {
  const leads = fetch("http://127.0.0.1:8000/api/v1/leads/", {method:'get', headers: {"Content-Type": "application/json"}})
  .then(function(result){
    //console.log("result", await result.text())
    return result.text()
  })
  .then(async function(result){
    // console.log("R2", result)
    allLeads = result.slice()
    // console.log("ALL", allLeads)
    callback(allLeads)
    return await leads
  })

My component class:我的组件类:

class Home extends React.Component {
  state = {
    dataType: "", // store the type of data for the type of operation that should be sent to the backend. For example "create" will have the data for creating data
    data: {},
    displayOptions: false
    } 


  leads = []
  async handleChange(event){
    event.preventDefault()
    this.state.displayOptions = true
  }

  render() {

      getAllLeads(function(data){
        console.log("DATA", data)
        return data
      })


    return (
        <div className="App">
          test

        </div>
      )

  }
}

export default Home;

In getAllLeads I'm successfully logging the data, but I have no idea how I would go about using that data inside my return function.getAllLeads我成功地记录了数据,但我不知道如何在返回函数中使用该数据。 Or how would I even use asynchronous data to set the state to a list for example so I could display the information inside the state?或者我什至如何使用异步数据将状态设置为列表,例如,以便我可以显示状态内的信息?

So there are a couple of problems there, first, to assign a value to the state you have to use this.setState({}) .所以这里有几个问题,首先, this.setState({})状态赋值,你必须使用this.setState({}) Since under the hood it will trigger a re-computation of the React Fiber.因为在引擎盖下它会触发 React Fiber 的重新计算。 Another suggestion I would give would be to trigger the API call on componentDidMount() lifecycle hook, you can make him async and then just await the result and call this.setState({ data }) .我给出的另一个建议是在componentDidMount()生命周期钩子上触发 API 调用,你可以让他异步,然后等待结果并调用this.setState({ data })

class Home extends React.Component {
  state = {
    dataType: "",
    data: {},
    leads: [],
    displayOptions: false
  }

 async componentDidMount() {
   const leads = await getAllLeads((data) => return data);
   this.setState({ leads });
 }

  render() {
    return (
        <div className="App">
          test

        </div>
      )

  }
}

export default Home;

I would also advise to refactor your function to get the leads since returning from inside a then returns nothing.我还建议重构您的函数以获取线索,因为从 a 内部返回然后不返回任何内容。 Use async and await instead.使用asyncawait代替。 Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM