Future memories
React setState: async render problem
Question 1: Does setState update properties asynchronously or synchronously? Does useState update properties asynchronously or synchronously?
Question 2: When is setState a synchronous rendered page and when is it an asynchronous rendered page
A demo: codesandbox.io/s/9oo7w? Fil…
One conclusion:
The setState is updated synchronously through the JS event binder addEventListener and using APIs such as setTimeout/setInterval that React cannot control
Under hook, obtain the latest state state through useEffect
Let’s get to the react-Redux
I don’t know where to start, so let’s start with one-way data flow. -!!!!!!
This is a one-way data flow, and suddenly I want to go back and consolidate MVC and MVVM. Let’s start with MVC and MVVM briefly. Jiong ~ ~ ~
So what is MVC? A concept of layered development. Since it’s a concept, can everyone fit into it anyway? How can the front end fit itself into it?
M: Modal, data source (State) V: View, View (HTML, CSS) C: Controller (JS)Copy the code
Backbonejs is a popular lightweight MVC front-end framework. Let’s take a backbone. js Todo Example. The following is the code snippet of its View component:
As you can see, the OPERATION of the DOM is intertwined with the JS logic at this point. So C directly operates on V, and V modifies M.
Finally, you have multiple models, multiple views in your Web application
How do, already can imagine the code is much, global search out, can not necessarily see understand
So let’s let unidirectional data flow do it.
Change state to make the view automatically updated
Get to know these three things:
Flux:Flux is a system architecture that facilitates the one-way flow of data across applications
Redux :Redux emphasizes three basic principles based on Flux
1: unique data source 2: keep the state read-only 3: Data changes can only be done through pure functions
- Defining the Action type
- Create the action constructor
- CreateStore with createStore: include update state reducer, initial state, (StoreEnhancer optional)
- Create reducer: The reducer contains the state and ATION parameters
- View partial initialization status: Get the status from store.getStore()
- Through the subscribe and unsubscribe synchronization state
- Change the store status by sending an action through store.dispatch
redux = Flux + reducer
The internal state flow of the store is smooth, so the next step is to string the Store and react components together.
- Working with the Redux Store, reading the state of the Store is used to initialize the state of the component, and listening for changes in the state of the Store. When the Store state changes, the component state needs to be updated to drive the component to re-render; When the Store status needs to be updated, the Action object is dispatched;
- Render the user interface based on the current props and state
If you find that a component does too many things, you can break it up into multiple components, each of which still focuses on one thing:
- The Component responsible for dealing with the Redux Store is in the outer layer and is called a Container Component.
- The component responsible for rendering the interface, located in the inner layer, is called a Presentation Component.
- Directly importing stores into components is very detrimental to component reuse
- Instead of having a component directly import into the Store, the component’s upper-layer components would have to pass the Store down. The problem with props, however, is that all components must help pass the props. React provides a feature called Context that solves this problem perfectly
So what’s the context in react? The official document gives:
Context provides a method to pass data across the component tree without having to manually add props for each layer of components.
Context allows you to “broadcast” this data to all components in the component tree, all of which have access to the data and to subsequent updates. Common scenarios for using context include managing the current locale, theme, or some cached data.
The official address: react.docschina.org/docs/contex…
React-Redux:
Redux: React-Redux: React-Redux: React-Redux: React-Redux: React-Redux: React-Redux: React-Redux: React-Redux: React-Redux
The react-Redux has two main features:
Provider: Provides a context that contains stores
The functions of the Provider module are not complicated. They are mainly divided into the following two points:Copy the code
- Wrap a layer on the original application component, so that the original application becomes a child component of the Provider
- Receive Redux’s store as props and pass it to connect on the descendant component via the Context object
Connect: Connects the container component to the fool component;
The Connect module actually connects React and ReduxCopy the code
import {Provider} from 'react-redux'
Copy the code
import {connect} from 'react-redux'; . export default connect(mapStateToProps,mapDispatchToProps)(Counter)Copy the code
Complete DEMO
//Counter.js
import * as Actions from '.. /Actions'
import {connect} from 'react-redux';
// Convert the state on the Store to the prop of the inner simpleton component
function mapStateToProps(state,ownProps){
return { value:state[ownProps.caption] }
}
Function mapDispatchToProps(dispatch,ownProps){
return{
onIncrement:() = >{
dispatch(Actions.increment(ownProps.caption))
},
onDecrement:() = >{
dispatch(Actions.decrement(ownProps.caption))
}
}
}
// Export the container components
export default connect(mapStateToProps,mapDispatchToProps)(Counter)
// Fool component
function Counter(props){
const {caption,onIncrement,onDecrement,value}=props
return( <div> <input type="button" onClick={onIncrement} value="+"/>
<input type="button" onClick={onDecrement} value="-"/>
<span>{caption}
count:{value}</span>
</div>)}Copy the code
//Summary.js
import {connect} from 'react-redux'
// Convert the state on the Store to the prop of the inner simpleton component
function mapStateToProps(state) {
let sum = 0;
for (const key in state) {
if(state.hasOwnProperty(key)) { sum += state[key]; }}return {value: sum};
}
function Summary({value}) {
return ( <div>Total Count: {value}</div> );
}
export default connect(mapStateToProps)(Summary);
Copy the code
//index.js
import store from './Store'
import {Provider} from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>.document.getElementById('root'));Copy the code
Data management tool
Flux
The order of Flux data flow is: View initiates Action->Action passes to Dispatcher->Dispatcher notifies Store->Store status changes notifies View of changes
Ps: based on the Flux architecture thought written a small demo
Redux
Redux improvements over Flux:
- The combination of Store and Dispatcher makes the structure more simple and clear
- Added the state role, which represents the value of the store at each point in time, to clarify state management
The order of Redux data streams is: View calls store.dispatch to initiate Action-> Store accepts Action(the Action is passed into the Reducer function, which returns a new state)-> notify the redo function of the store.subscribe subscription
Ps: Redux+React demo by Ruan Yifeng
Vuex
Vuex is a state management framework specially designed for Vue. It is also based on Flux architecture and absorbs the advantages of Redux. The differences between Vuex and Redux are as follows:
- Action and Reducer functions in Redux are improved, instead of Reducer, mutations change function is used.
- No switch is required, just change the state value in the corresponding mutation function
- Because of Vue’s automatic rerender feature, there is no need to subscribe to the rerender function, just generate the new State
The sequence of Vuex data streams is: View calls store.com MIT to submit the corresponding request to the corresponding mutation function in Store -> Store change (VUE automatically renders the data changes detected)
Ps: Vuex official Vue+ Vuex demo
Asynchronous processing in state management
Finally, one question is why asynchronous processing is separate from Vuex and Redux?
A function that changes state must be a pure function. A pure function is a uniform input and a uniform output without any side effects. If asynchronous, it introduces the additional side effect of making the changed state unpredictable;
Both Vuex and Redux are state management mechanisms. Then they will have their own state and their own method of modifying state, and the method of modifying state involves both synchronization and asynchron. Vuex handles this by synchronizing in mutation, asynchron in Actions, Then, the synchronization of Redux is reducer, and the asynchronization is more realized by the users themselves through the middleware (redux-thunk redux-saga).
“Yuda replied
Actions and mutations are not designed to solve race problems, but to track state changes using DevTools.
In fact, actions in Vuex is an architectural concept, not a necessary one. In the end, actions is just a function, and you can do whatever you want in it, as long as the mutation is triggered last.