iT邦幫忙

第 11 屆 iT 邦幫忙鐵人賽

DAY 24
0

Day 23 - AJAX 與 Fetch API

上一章介紹了AJAX與Fetch API, 還有其使用方式

我們今天來實作看看

新增Member.js

import React, { Component } from 'react';
import { Container, Table } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.css';

class Member extends Component {

	constructor(props) {
		super(props);
		this.state = { members: [] };
	}

	componentDidMount() {
		fetch('api/members').then(response => response.json())
			.then(data => this.setState({ members: data }));
	}

	render() {
		const { members } = this.state;

		const memberList = members.map(member => {
			return <tr key={member.mid}>
                <td>{member.email}</td>
                <td>{member.password}</td>
                <td>{member.firstName}</td>
                <td>{member.lastName}</td>
			</tr>
		});

		return (
			<div>
				<MyNavbar />
				<Container fluid>
					<h3>Member</h3>
					<Table className="mt-4">
						<thead>
							<tr>
								<th>Email</th>
								<th>Password</th>
								<th>FirstName</th>
								<th>LastName</th>
							</tr>
						</thead>
						<tbody>
							{memberList}
						</tbody>
					</Table>
				</Container>
			</div>
		);
	}

}
export default Member;

App.css新增container-fluid

.container, .container-fluid {
margin-top: 10px;
}

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Member from './Member';

class App extends Component {
	render() {
		return (
			<Member />
		);
	}

}

export default App;

設定向後端請求資料的路徑

package.json

"proxy": "http://localhost:8080"

按快捷鍵CTRL + ` 打開Terminal, 輸入npm start執行

畫面就出來了

https://ithelp.ithome.com.tw/upload/images/20191010/20119510VuN5aXMPGi.png

下一章 Day 25 - React Fetch 向後端API請求資料(2)


上一篇
Day 23 - AJAX 與 Fetch API
下一篇
Day 25 - React Fetch 向後端API請求資料(2)
系列文
Spring Boot and React - 前後端 30 天分手日記30

尚未有邦友留言

立即登入留言