Skip to main content

[note] Fetching data by React Hooks

這篇文章主要整理自 How to fetch data with React Hooks?,這篇文章同時也被列在 A Complete Guide to useEffect by Dan Abramov 的推薦閱讀中,因此建議大家可以回頭看這篇原始文章。

在這個範例中使用了 useState, useEffectuseReducer,你也可以直接看完成的程式碼 code sandbox

完整程式碼 @ code sandbox

起始樣板

/**
* https://www.robinwieruch.de/react-hooks-fetch-data
*/
// ./src/index.js

import React from 'react';
import ReactDOM from 'react-dom';

import './styles.css';

function App() {
return (
<div className="App ">
<h1>Fetch data with React Hooks</h1>
<div className="pure-form">
<div className="pure-control-group">
<input type="text" className="pure-input-rounded" />
<button type="button" className="pure-button button-small">
Search
</button>
</div>
</div>
<div className="pure-menu">
<ul className="pure-menu-list">
<li className="pure-menu-item">
<a href="#" className="pure-menu-link">
Hello React
</a>
</li>
<li className="pure-menu-item">
<a href="#" className="pure-menu-link">
Hello React Hooks
</a>
</li>
<li className="pure-menu-item">
<a href="#" className="pure-menu-link">
Hello React and Redux
</a>
</li>
</ul>
</div>
</div>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
/* ./src/styles.css */
.App {
font-family: sans-serif;
text-align: center;
padding: 60px;
}

.pure-form {
margin-bottom: 30px;
}

.pure-menu {
text-align: left;
}

.pure-input-rounded {
margin-right: 15px;
}