简体   繁体   English

如何正确调用reactjs渲染方法中的函数?

[英]how to call function inside reactjs render method properly?

I want to fetch data from server & show it inside tables. 我想从服务器获取数据并在表中显示。 When I directly put code inside the render it works. 当我直接将代码放入渲染器时,它可以工作。 But, When I encapsulate inside the addElementsToDisplay function & call that function inside render method it doesn't work. 但是,当我将其封装在addElementsToDisplay函数中并在render方法中调用该函数时,它将无法正常工作。 Actually, the function gets called, but response is not rendered in table format. 实际上,该函数被调用,但是响应不是以表格格式呈现。 Below is my code: 下面是我的代码:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Button } from 'semantic-ui-react';
import ResponseRenderer from './responseRenderer';
import "./App.css";

const responseDataContext = React.createContext({});



class App extends Component {
    constructor(props) {
    super(props);
    this.getPastJobs = this.getPastJobs.bind(this);
    this.addElementsToDisplay = this.addElementsToDisplay.bind(this);
    this.state = { pastJobs: [] }
  }

  render() {
    return (
      <div className="App">
        <Button onClick={this.getPastJobs}>Get Past Jobs</Button>
        <h1> Hello, World! </h1>
        {this.addElementsToDisplay()}
      </div>
    );
  }

  addElementsToDisplay() {
    console.log("state: ", JSON.stringify(this.state));
    this.state.pastJobs.map((value, index) => {
      return <ResponseRenderer key={Math.random()} data={value} />
    });
  }


  getPastJobs() {
    fetch('http://localhost:9090/getPastJobs', {
     method: 'POST',
      body: JSON.stringify({})
    })
      .then((response) => {
        if (response.status !== 200) {
          return;
        }
        response.json().then((jobs) => {
          console.log(jobs);
          this.setState({ pastJobs: jobs.data })
        });
      })
      .catch((err) => {
        console.log(err.message, err.stack);
      });
  }
}

export default App;

You are not returning the response and hence it is not rendered, just return the mapped response and it will work fine 您不会返回响应,因此不会呈现它,只需return映射的响应,它将可以正常工作

addElementsToDisplay() {
    console.log("state: ", JSON.stringify(this.state));
    return this.state.pastJobs.map((value, index) => {
      return <ResponseRenderer key={Math.random()} data={value} />
    });
  }

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

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