上一章介紹了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執行
畫面就出來了
下一章 Day 25 - React Fetch 向後端API請求資料(2)