React 筆記
更新換到我的 Github
Contents:
+ Components
+ JSX
+ Hooks
+ Higher-Order Components
+ React router
+ Redux
+ Other References
Components
The main building block for the applications is a Component
.
Class components should always call the base constructor with props
:
constructor(props) {
super(props);
this.state = {date: new Date()};
}
Two main patterns for sharing code
- Higher-order components
- Render props
state vs. props
state
is similar toprops
, but it is private and fully controlled by thecomponent
.
JSX
References
Hooks
Hooks are functions provided by react that lets you “hook” into React features from your “function components”
useState Hook
useState
讓我們可以在 function component 保留 local state- 每一次更新 state , React 就會 re-render function component
useEffect Hook
- Runs a function every render of the components
The dependency array
(a second argument of useEffect) => trigger for useEffect Hook
useEffect(() => {}, []); // with an empty dependency array, it runs function only once, after the first initial render
useEffect
can return a function which is used to clean up (replacecomponentWillUnmount()
in class component)
custom Hook
Just remember to name your custom Hook beginning with use
(i.e. useWindowWidth
, useXXXXXX
)
useRef Hook
Very useful for persisting values across renders without actually causing a rerender.
Common use cases:
- To focus the element (i.e.
<Input />
) - Store the previous state
References
Higher-Order Components
Concretely, a higher-order component is a function that takes a component and returns a new component.
const EnhancedComponent = higherOrderComponent(WrappedComponent);
References
React router
- Server responds
html
+js bundle
npm install react-router-dom
About <Redirect>
<Redirect>
comes in handy in specific situations though, an example is when a 404
page is rendered when the user tries to access an undefined route. The <Redirect>
will redirect the user from the 404 route to a new route of your choosing, and then replace the last entry in the history stack with the redirected route.
This means that the user will not be able to hit their browser’s back button, and return to the 404 route.
come in handy = to be useful
Some tips
- It is better to always have
<Switch><Switch/>
surrounding the<Route>
- Use
<Link>
to prevent the request to the server
References
[1] React-Router — Link vs Redirect vs History
Redux
- A state management tool
- Redux 經常與 React 搭配運用,但其也可以獨立使用