📄 Directory Structure
- What is a Redux?
- When to use Redux?
- How to use React-redux?
- Redux term
- How to use the Redux Toolkit?
🔖 Demo
The title | Demo |
---|---|
react-redux | Demo |
redux toolkit | Demo |
What is a Redux?
It’s a solution for the state management, what is the state? React state. As logic becomes more complex, we need to introduce a layer to do state management, and Redux is one of those layers.
Let’s start with a simple counter component:
function Counter() {
// State: counter value
const [counter, setCounter] = useState(0);
// Action: Updates the status when an operation occurs
const increment = () = > {
setCounter(prevCounter= > prevCounter + 1)}// View: UI definition
return (
<div>
value: {counter}
<button onClick={increment}>Increment</button>
</div>)}Copy the code
This counter component can be divided into three phases:
In the first phase, we define a counter state in the component; We then use this counter state to define the VIEW layer’S UI structure, UI content; When we click the button in the view layer, we can trigger this state update, which is the Action.
So the three stages are:
- State: indicates the counter value
- Action: Updates the status when an operation occurs.
- View: UI definition.
When to use Redux?
Redux only pays if the application is complex enough, otherwise it just adds complexity to our entire application.
Two questions are raised here:
- Suppose b2-B3 is in a shared state, what should we do?
- What if b2-A2 components have components that need to be shared?
There is a specific solution to problem 1 called state escalation. To raise the state shared by B2 and B3 to level B1.
The component B1 manages the common state, and then passes the props to B2 and B3, so that both B2 and B3 can use the state of B1.
For problem 2, we upgraded the common states of A1 and B2 to A1 according to the principle of state promotion, and then A1 returned to B2 through B1. At this time, we had some trouble in solving state sharing through state promotion.
The more complex the hierarchy of the component tree is and the farther apart the nodes to be shared are, the greater the level of difference, and the greater the complexity of the problem solved by state promotion.
Introducing a global state management approach through Redux allows components at any level to access state directly from Redux when they need it.
The problem of requiring layers of component delivery is avoided.
How to use React-redux?
Let’s take implementing a calculator as an example:
When we press “addend” on the page, we see the result of 0 becoming 2. In fact, the internal procedure is executed by calling a method through the onClick event.
The addAmount method in onClick returns actions that dispatch passes to the reducer. Reducer judged according to the type in the action and returned the calculation result, and the state was updated on the page.
That’s how you go from 0 to 2 on the page.
The implementation logic is abstracted as follows:
As a beginner’s project, my SRC directory is as follows,
| – index. Js entry documents
| – App. Js entrance components
| – Counter. Js calculator component
| – store. Js the whole project only save the data, can be as a container
| – reducer. Js receives the action and help store to generate the calculation process of the state
| – actions. Js triggered the user on a web page
| – styles. CSS file
// index.js
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { store } from "./store";
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
,
rootElement
);
Copy the code
The store is provided through the Provider at the entrance, so that no matter how many components are behind it, state can be retrieved through useSelector.
Redux term
import { configureStore } from '@reduxjs/toolkit'
const store = configureStore({ reducer: counterReducer })
console.log(store.getState())
Copy the code
Reduxjs/Toolkit is based on Redux, Redux Toolkit, referred to as RTK. Use redux through this library to make things even more concise.
The store can be created by importing configureStore from the RTK library. The reducer object is passed in configure.
Using the getState save method, we can get the state saved in the store.
How to use the Redux Toolkit?
We learn by adding and subtracting counting examples:
The directory structure is as provided in the official documentation:
- app
- store.js
- features
- counter
- Counter.js
- counterSlice.js
- counter
- App.js
- index.js
- styles.css
Of particular note is that it has one more file called counterSlice than React-Redux, so we’ll focus on that.
// counterSlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
value: 0
};
export const counterSlice = createSlice({
name:"counter",
initialState,
reducers: {
increment: (state) = > {
The Redux Toolkit allows us to compile "mutating" logic in the Reducer.
// state.value+=1 it doesn't actually change state, it's a pure function.
// Because it uses the Timmer library, it detects changes in the 'draft state'
// And a new immutable state is created based on these changes
state.value += 1;
},
decrement: (state) = > {
state.value -= 1;
},
incrementByAmount: (state, action) = >{ state.value += action.payload; }}});Copy the code