In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you "what are the basic knowledge points of Redux", which is easy to understand and well organized. I hope it can help you solve your doubts. Let me lead you to study and learn this article "what are the basic knowledge points of Redux?"
What is Redux?
A State manager that centralizes the various states in the application.
All states are stored in one object, and Redux is the same as the unified read and write mechanism.
Although Redux does not have any direct relationship with React, the main purpose of Redux (almost the only use) is to serve React, to manage the state of components and to simplify the invocation relationship of component states in complex applications.
What are the main uses of Redux
1) provide a container for centralized state management.
2) provide a set of read and write state mechanism and state change listening response mechanism.
3) cooperate with React to achieve automatic rendering, with one State corresponding to one View. As long as the State is the same, View is the same. You know State, you know what View is like, and vice versa.
How to use it?
1) create a unique store:
Import {createStore} from 'redux'; / / reducer explains later that createStore needs to pass in a reducer or reducer collection. Const reducer = function (oldstate, action) {return newstate;} const store = createStore (reducer)
2) obtain state
Const state = store.getState ()
3) to change state, you need to send action notification.
Although Redux can change the state of a component through setState, only dispatch can be used in redux to send action to change state.
An action is a notification from anyone that State is about to change.
The method to send notifications is store.dispatch (action). As follows:
Import {createStore} from 'redux'; const store = createStore (fn); store.dispatch ({type:' ADD_TODO', payload: 'Learn Redux'})
The structure of Actiond:
Const action = {type: 'ADD_TODO', payload:' Learn Redux'}
Type is required to identify that an action,payload is optional and carries any data to be passed.
You can write some helper functions to create action to prevent dispatch from looking too complicated.
4) Reducer
After Store receives the Action, a new State must be given. The process of calculating this State is called Reducer.
Reducer is a function that takes Action and the current State as arguments and returns a new State.
This function is created in store and is passed in, as described above: const store = createStore (fn), that is:
Const store = createStore (reducer)
Every time a new Action is sent by store.dispatch, Reducer is automatically called to get a new State.
The most important feature of the Reducer function is that it is a pure function.
Pure functions are the concept of functional programming and must comply with some of the following constraints.
The parameters cannot be rewritten, the API of the system Icano cannot be called, and impure methods such as Date.now () or Math.random () cannot be called, because different results will be obtained each time.
Because Reducer is a pure function, the State cannot be changed in the Reducer function, and a brand new object must be returned.
5) store.subscribe ()
Store allows you to set a listener function using the store.subscribe method, which is automatically executed whenever the State changes.
Import {createStore} from 'redux'; const store = createStore (reducer); store.subscribe (listener)
Obviously, as long as you put the update function of View (for React projects, the render method or setState method of the component) into listen, you will achieve automatic rendering of View (this depends on React-Redux).
The store.subscribe method returns a function that can be called to delisten.
Let unsubscribe = store.subscribe (()) = > console.log (store.getState ()); unsubscribe (); implementation of Store
Having introduced the basic concepts involved in Redux above, you can see that Store provides three methods.
Store.getState () store.dispatch () store.subscribe () import {createStore} from 'redux'; let {subscribe, dispatch, getState} = createStore (reducer)
The createStore method can also accept a second parameter that represents the initial state of the State. This is usually given by the server.
Let store = createStore (todoApp, window.STATE_FROM_SERVER)
In the above code, window.STATE_FROM_SERVER is the initial state value of the entire application. Note that if this parameter is provided, it overrides the default initial value of the Reducer function.
Here is a simple implementation of the createStore method to see how Store is generated. (the following code is only used to understand the principle and belongs to the advanced tutorial)
Const createStore = (reducer) = > {let state; let listeners = []; const getState = () = > state; const dispatch = (action) = > {state = reducer (state, action); listeners.forEach (listener = > listener ());}; const subscribe = (listener) = > {listeners.push (listener) Return () = > {listeners = listeners.filter (l = > l! = = listener);}}; dispatch ({}); return {getState, dispatch, subscribe};}; split of Reducer
The Reducer function is responsible for generating State. Because the whole application has only one State object, which contains all the data, for large applications, the State must be very large, resulting in the Reducer function is also very large.
Take a look at the example below.
Const chatReducer = (state = defaultState, action = {}) = > {const {type, payload} = action; / / unpack switch (type) {case ADD_CHAT: return Object.assign ({}, state, {chatLog: state.chatLog.concat (payload)}) Case CHANGE_STATUS: return Object.assign ({}, state, {statusMessage: payload}) Case CHANGE_USERNAME: return Object.assign ({}, state, {userName: payload}); default: return state;}
In the above code, the three Action changes the three properties of the State respectively.
ADD_CHAT:chatLog attribute
CHANGE_STATUS:statusMessage attribute
CHANGE_USERNAME:userName attribute
There is no connection between these three attributes, which suggests that we can split the Reducer function. Different functions are responsible for handling different properties and eventually merge them into one large Reducer.
Const chatReducer = (state = defaultState, action = {}) > {return {chatLog: chatLog (state.chatLog, action), statusMessage: statusMessage (state.statusMessage, action), userName: userName (state.userName, action)}}
In the above code, the Reducer function is split into three small functions, each of which is responsible for receiving the corresponding state, processing the corresponding action, and returning the corresponding state.
In this way, Reducer is much easier to read and write. Moreover, this split is consistent with the structure of React applications: a React root component is made up of many sub-components. That is to say, the subcomponents and the child Reducer can correspond perfectly.
Redux provides a combineReducers method for splitting Reducer. All you have to do is define each sub-Reducer function and then use this method to synthesize them into a large Reducer.
Import {combineReducers} from 'redux'; const chatReducer = combineReducers ({chatLog, statusMessage, userName}) export default todoApp
The above code merges the three child Reducer into one large function through the combineReducers method.
A prerequisite for this writing is that the attribute name of the State must have the same name as the child Reducer. If the name is different, it should be written as follows.
Const reducer = combineReducers ({a: doSomethingWithA, b: processB, c: C}) / / equivalent to function reducer (state = {}, action) {return {a: doSomethingWithA (state.a, action), b: processB (state.b, action), c: C (state.c Action)}}
In short, what combineReducers () does is produce an overall Reducer function. This function executes the corresponding child Reducer according to the key of State and merges the returned results into one large State object.
Here is a simple implementation of combineReducer (implementation, which tells you how it works, why).
Const combineReducers = reducers = > {return (state = {}, action) = > {return Object.keys (reducers). Reduce ((nextState, key) = > {nextState [key] = reducers [key] (state [key], action); return nextState }, {});}
You can put all the sub-Reducer in one file, and then introduce them (this sentence is practical information).
For import {combineReducers} from 'redux' import * as reducers from'. / reducers' const reducer = combineReducers (reducers), how each reducer handles the corresponding status, you need to refer to the following text to make it clearer:
Https://blog.51cto.com/livestreaming/2313439 workflow
This section combs the workflow of Redux.
First, issue the Action.
Action can be sent from anywhere, triggered by interface operations, time, server messages, etc., for the purpose of telling Store that I want to change a certain state.
Store.dispatch (action)
Store then automatically calls Reducer, passing in two parameters: the current State and the received Action. Reducer returns the new State.
Let nextState = todoApp (previousState, action)
Whenever there is a change in State, Store calls the listening function.
/ / set listening function
Store.subscribe (listener)
Listener can get the current state through store.getState (). If you are using React, you can trigger a re-rendering of View.
Function listerner () {let newState = store.getState (); component.setState (newState);}
React-Redux actually has a more automated approach, please refer to:
Https://daveceddia.com/how-does-redux-work/
How does Redux trigger a change in the component view?
This is the content of React-Redux, you need to connect the component into redux, if there is no connect, there will be no automatic change of component view.
It's like this:
Function mapStateToProps (state) {return {count: state.count};} export default connect (mapStateToProps) (MyCompnent); these are all the contents of this article entitled "what are the basic knowledge points of Redux?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.