[英]Connect ReactJS frontend to REST API in spring
Based on the tutorial on this page: https://spring.io/guides/tutorials/react-and-spring-data-rest/ I am trying to create a frontend to my Spring REST API backend. 我對這些示例進行了一些修改,以適應我在 spring 中的項目,但不幸的是它現在不起作用。 現在,我只是想從主頁上的數據庫中寫出一些記錄。 將出現一個空白的白頁,而不是來自數據庫的文本。
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}]
@RequestMapping(value = "/getAllDelegations", method = RequestMethod.GET)
@ResponseBody
public List<Delegation> getAllDelegations(){
return delegationService.findAll();
}
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
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')
)
誰能告訴我我在哪里犯了錯誤? 我會很感激。
當您使用 componentDidMount 委托組件時,已呈現並且收到的新道具不會更新組件。
我建議您將委托功能組件轉換為 class 組件並使用 componentWillReceiveProps 方法在收到道具時更新 state
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 Delegations
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.