我想从服务器获取数据并将其显示在表格中。当我直接将代码放入渲染中时,它就可以工作。但是,当我封装在 addElementsToDisplay 函数内并在渲染方法内调用该函数时,它不起作用。实际上,该函数被调用,但响应并未以表格格式呈现。下面是我的代码:
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;
最佳答案
您没有返回响应,因此它不会呈现,只需返回
映射的响应,它就会正常工作
addElementsToDisplay() {
console.log("state: ", JSON.stringify(this.state));
return this.state.pastJobs.map((value, index) => {
return <ResponseRenderer key={Math.random()} data={value} />
});
}
关于javascript - 如何正确调用reactjs渲染方法中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50190102/