首页 > 解决方案 > 在 Spring 中将 ReactJS 前端连接到 REST API

问题描述

基于此页面上的教程: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')
    )

谁能告诉我我在哪里犯了错误?我会很感激。

标签: javareactjsspring

解决方案


当您使用 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 Delegations

推荐阅读