基于本页面上的教程:https://spring.io/guides/tutorials/react-and-spring-data-rest/,我正在尝试创建Spring REST API后端的前端。我对这些示例进行了一些修改,以适应我在春季的项目,但不幸的是,它现在不能工作。现在,我只想在主页上从数据库中写出几条记录。此时将显示空白页,而不是数据库中的文本。
在这里,您可以看到curl打印输出:
C:\Users\Admin>curl http://localhost:8080/getAllDelegations
[{"delegationId":3,"user":{"userId":3,"role":[],"companyName":"PeterCorp","companyAddress":"Wojty┼éy 12 88-T99 bydgoszcz","companyNip":"11111111111","name":"Jan","lastName":"Kowalski","email":"TEST@gmail.com","password":"1234","status":true,"registrationDate":"2020-03-31T13:29:51.142+0000","delegations":[]},"description":"efa","dateTimeStart":"2020-03-31T15:34:00.134+0000","dateTimeStop":"2020-03-31T15:34:00.134+0000","travelDietAmount":0.0,"breakfastNumber":0,"dinnerNumber":0,"supperNumber":0,"transportType":"AUTO","ticketPrice":0.0,"autoCapacity":true,"km":0,"accomodationPrice":0.0,"otherTicketsPrice":0.0,"otherOutlayDesc":0.0,"otherOutlayPrice":0.0}]我的来自Controller类的java方法:
@RequestMapping(value = "/getAllDelegations", method = RequestMethod.GET)
@ResponseBody
public List<Delegation> getAllDelegations(){
return delegationService.findAll();
}DelegationsTest.js -此文件应打印出数据库中的数据:
import React from 'react';
const Delegations = (props) => {
return (
<div>
<center><h1>Delegations List</h1></center>
props.delegations.map((delegation) => (
<div>
<div>
<h5>{delegation.delegationId}</h5>
<h6>{delegation.user.lastName}</h6>
<p>{delegation.user.companyName}</p>
</div>
</div>
))
</div>
)
};
export default Delegations我的主app.js文件:
const React = require('react');
const ReactDOM = require('react-dom');
import Delegations from './components/DelegationsTest';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
delegations: []
};
}
componentDidMount() {
fetch('http://localhost:8080/getAllDelegations')
.then(res => res.json())
.then((data) => {
this.setState({ delegations: data })
})
.catch(console.log)
}
render() {
return (
<div>
<h1>HelloWorld</h1>
<div>
<Delegations delegations={this.state.delegations} />
</div>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('react')
)有没有人能告诉我我哪里出了错?我会非常感激的。
发布于 2020-04-16 02:56:56
由于您正在使用componentDidMount,委派组件已经呈现,并且收到的新属性不会更新该组件。
我建议您将委托功能组件转换为类组件,并在收到属性时使用componentWillReceiveProps方法更新状态
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
delegations: props.delegations
};
}
componentWillReceiveProps(nextProps) {
this.setState({
delegations: nextProps.delegations
})
}
render() {
return ( <
div >
<
center > < h1 > Delegations List </h1> </center >
this.state.delegations.map((delegation) => ( <
div >
<
div >
<
h5 > {
delegation.delegationId
} < /h5> <
h6 > {
delegation.user.lastName
} < /h6> <
p > {
delegation.user.companyName
} < /p> <
/div> <
/div>
)) <
/div>
)
};
}
export default Delegationshttps://stackoverflow.com/questions/61209373
复制相似问题