Redux is a data state management plug-in. When using React or vue to develop componentized SPA programs, sharing information between components is a very big problem. For example, after the user logs in, the client will store user information (ID, avatar, etc.), and many components of the system will use this information. When using this information, they will re-get it every time, which will be very troublesome. Therefore, each system needs a function to manage the public information used by multiple components, which is what redux does.
If you have never been exposed to redux, I hope you can take a look patiently. I am also optimistic about many blogs and summarized them myself! ! ! ! It is a little better than the big guys to find one by one.
import React, { Component, Fragment } from 'react'; //Class introductionimport { connect } from 'react-redux'; //Hook introductionimport { useSelector, useDispatch } from 'react-redux' import { add, clear } from '../../redux/actions/count'; //hook display componentconst CountItem = (props) => { // Deconstructed const { count, flag, add, clear } = props return ( <> <h2>The current sum is:{count}</h2> <h3>currentFlag:{flag ? 'true' : 'false'}</h3> <button onClick={add}>Click+1</button> <button onClick={clear}>Clear</button> </> ) } //hook container componentconst Count = () => { const count = useSelector(state => ) const flag = useSelector(state => ) const dispatch = useDispatch() const countAdd = () => { () dispatch(add(1)) } const clearNum = () => { dispatch(clear()) } return <CountItem count={count} flag={flag} add={countAdd} clear={clearNum} /> } export default Count // class display component// class Count extends Component { // add = () => { // // Notify redux// (1); // }; // clear = () => { // (); // }; // render() { // return ( // <Fragment> // <h2>The current sum is: {}</h2>// <h3>Current Flag: { ? 'true' : 'false'}</h3>// <button onClick={}>Click +1</button>// <button onClick={}>Clear</button>// </Fragment> // ); // } // } // class container component// export default connect( // // 1. Status// state => ({ count: , flag: }), // // 2. Method// { add, clear } // )(Count);
This is the basic usage. The key method we use on hooks is to useSelector to use redux state, use dispatch to call reduce; use connect to the state and method (reduce) in the class component.
The difficulty lies in reducing and state
What is the reduce here
In the above code, we use the two methods: add and clear. We create a new js file to implement these two methods.
// Create an action object for the Count component// Introduce constantsimport { ADD, CLEAR } from '../constant'; // Create a function that adds an action objectexport const add = data => ({ type: ADD, data, }); // Create a function that clears the action objectexport const clear = data => ({ type: CLEAR, data, });
There are constants above----This is to facilitate the unified management of actionType. Creating corresponding action objects helps to modularize the code.
Post it, build one yourself and put it in
export const ADD = 'add'; export const CLEAR = 'clear';
At this point, our action object is almost defined, and we need to manage reducer. That is, dispatch distribution above action objects to realize state update
In the reducer folder we define a
// Create a reducer for the Count component// reducer receives two parameters: preState in previous state, action object action import { ADD, CLEAR } from '../'; // Set the initial stateconst initState = 0; export default function addReducer(preState = initState, action) { // Get type and data from action const { type, data } = action; // Decide how to process data according to type switch (type) { case ADD: return preState + data; case CLEAR: return 0; // Initialize the action default: return preState; } }
The above method needs to use dispatch to type distribution call (emphasis added one)
It's done here. Next, let's configure redux to react project
Don’t flashbacks here, because flashbacks here are unreasonable.
Several key configurations here
Configuration and global store usage
First look at the global use of the store
Wrap the App with Provider under your root route.
import React from 'react'; import ReactDOM from 'react-dom'; import App from './'; import store from './redux/store'; import { Provider } from 'react-redux'; ( // Provider wraps the App, purpose: to enable all descendant container components of the App to receive the store <Provider store={store}> <App /> </Provider>, ('root') );
There is a redux/ code here
// There is only one store object in the entire document. CreateStore receives two parameters. The first is the state tree and the second is the action to be processed.//applyMiddleware summarizes all middleware and turns into an array to execute in sequence, and process asynchronouslyimport { createStore, applyMiddleware } from 'redux'; //middlewareimport thunk from 'redux-thunk'; //Summarize all reducersimport allReducers from './reducers/index'; //This is Google's debugging and debugging tool, specific use: Baiduimport { composeWithDevTools } from 'redux-devtools-extension'; // Expose storeexport default createStore(allReducers, composeWithDevTools(applyMiddleware(thunk)));
This article is about to end here. I don’t understand some of the execution processes and principles in it yet. I still need to consolidate and learn more in the future.
The above is the detailed content of the article solving the initial use of redux in react. For more information about the use of redux in react, please pay attention to my other related articles!