This is the third day of my participation in the August Text Challenge.More challenges in August”
React can be used in react, and spa can be used in React
preface
In today’s single-page front-end applications, React and Vue have their own parameter transfer methods, which are indispensable in our work. Besides the internal parameter transfer methods provided by the framework, there are third-party parameter transfer methods such as Mobx or Redux. Of course, these are the most popular methods used in the React ecosystem, as well as the methods provided by browsers, such as session and local, etc. Since today we will focus on React, the following examples will be implemented using React
introduce
In React, some operations only change the stored value, and only get the value of the response after manually triggering the update. To ensure the update, functions and context are transmitted across layers, including the libraries Redux and Mobx, using the API provided by the libraries and the React binding. The update will not be triggered by the browser that stores the parameters
In the following cases, hooks will be used, which are used in special cases such as several uses of context
Succession and
The parent component passes some parameters to the child component, and the child component receives most of the observable data through props. When the parent component changes the parameters transmitted to the child component, the child component responds to the update and renders the new content normally
import { useState } from "react";
const Son = (props) = > {
//props receives the parameter when the name changes to the child component to re-render
const { name } = props;
return <h1>{name}</h1>;
};
const Person = () = > {
const [name, setName] = useState("If you don't say anything, you'll be a great man."); // Define initialization parameters
return (
<div>{/* Parent */}<Son name={name} />{/* Update the parameter */}<span onClick={()= >}> update</span>
</div>
);
};
export default Person;
Copy the code
Son of the father to participate
The parent component passes a callback method to the child component, which then calls the callback method to pass parameters to the parent component. Let’s look at the code
import { useState } from 'react'
const Person = () = > {
const [count, setCount] = useState(0)
const updateCount = (val) = > {
setCount(val)
}
return <div>{/* Define the callback method */}<Son callback={updateCount} />Thumb up: {count}</div>
}
const Son = (props) = > {
const { callback } = props
return <div>{/* Call the method passed by the parent component and pass the argument */}<button onClick={()= >Callback (10)}> Updates the parent component</button>
</div>
}
export default Person;
Copy the code
Context is passed across hierarchies
Context is the main way to pass parameters across hierarchies. There are currently three ways to pass parameters across hierarchies: in class, in hooks, and in general, which we’ll look at in turn
In the Class component use contextTypes in the parent component and this.context in the child component
import React from 'react'
import PropTypes from 'prop-types';
class SecondComp extends React.Component {
static contextTypes = {
// Child component declares receive parameters
name: PropTypes.string
}
render() {
return <div>SecondComp {this.context.name}</div>}}class FirstComp extends React.Component {
render() {
return <div>Parent component: FirstComp<SecondComp />
</div>}}class App extends React.Component {
state = {
name: 'Sunset clouds and lone ducks fly together.'
}
getChildContext() {
// Define parameters in the parent component
return { name: this.state.name };
}
static childContextTypes = {
name: PropTypes.string
}
render() {
return <div>Ye components: App<button onClick={()= >This.setstate ({name: 'autumn water is the same color'})}> Update</button>
<FirstComp />
</div>}}export default App;
Copy the code
The general method for passing context arguments uses the keywords Provider and Consumer. This 🌰 section only shows examples of class components because hooks use the same method as class components
// Declare public context
const ThemeContext = React.createContext(' ');
class SecondComp extends React.Component {
render() {
// With Consumer nesting, children receive a callback function whose arguments are passed by the parent component
return <ThemeContext.Consumer>
{
(val) => <div>SecondComp {val}</div>
}
</ThemeContext.Consumer>}}class FirstComp extends React.Component {
render() {
return <div>Parent component: FirstComp<SecondComp />
</div>}}class App extends React.Component {
state = {
name: 'Sunset clouds and lone ducks fly together.'
}
render() {
return <div>Ye components: App<button onClick={()= >This.setstate ({name: 'autumn water is the same color'})}> Update</button>{/* The parent component uses Provider nesting to pass arguments */}<ThemeContext.Provider value={this.state.name}>
<FirstComp />
</ThemeContext.Provider>
</div>}}export default App;
Copy the code
Cross – hierarchy parameters are implemented in hooks using useContext to receive parameters
// Declare public context
const ThemeContext = React.createContext(' ');
const SecondComp = () = > {
const { name } = useContext(ThemeContext)
return <div>SecondComp {name}</div>
}
const FirstComp = () = > {
return <div>Parent component: FirstComp<SecondComp />
</div>
}
const App = () = > {
const [name, setName] = useState('Sunset clouds and lone ducks fly together.')
return <div>Ye components: App<button onClick={()= >SetName (' Autumn water together ')}> update</button>{/* Pass parameters */}<ThemeContext.Provider value={{
name}} >
<FirstComp />
</ThemeContext.Provider>
</div>
}
export default App;
Copy the code
State library parameters are passed
Mobx and Redux are two popular types of state management in the React ecosystem. Mobx and Redux are the two most popular types of state management in the React ecosystem
Mobx, similar to VUex, uses responsive listening. Mobx provides binding of observe and react views to respond to data changes. Note that @ can be used only when a decorator is configured in JS
Defining store storage
//npm i -D mobx mobx-react
import { observable, action } from 'mobx'
class Store {
@observable count = 0
@action.bound
seetCount(){
this.count = 100}}export default new Store()
Copy the code
Connect the observe view to the React view
import Store from './store'
import { observer } from 'mobx-react'
const Son = () = > {
return <div>State management provides: {store.count}</div>
}
const SonOb = observer(Son)
const Person = () = > {
return <div>
<SonOb/>
<button onClick={Store.seetCount(100)}></button>
</div>
}
export default observer(Person);
Copy the code
Redux storage is a popular one, and it is not tied to the framework itself, and it does not have a deep binding relationship with Vue like Vuex. Redux provides connect higher-order function and view connection, but we will not use it today. I will update the view according to the monitoring update function provided by Redux. Use useReducer directly to force updates
Defining store storage
import { createStore } from 'redux'
// Pure function mode
function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
returnstate; }}const store = createStore(counter);
export default store
Copy the code
The react view
import { useEffect, useReducer } from 'react'
import store from './store/store'
function Son() {
return <div>
<span>The state library provides arguments: {store.getState()}</span>
Son
</div>
}
function Person() {
const [, forceUpdate] = useReducer(x= > x + 1.0)
useEffect(() = > {
//redux updates the monitoring function
store.subscribe(() = > {
forceUpdate()
}
);
}, [])
return (
<div className="App">
<Son />
<button onClick={()= >Store.dispatch ({type: 'INCREMENT'})}> Update</button>
Person
</div >
);
}
export default Person;
Copy the code
Only the react parameter transfer method can automatically update views, while the state library can be updated in a timely manner only by binding its own API to the view. The following is a general storage method that does not distinguish between frameworks. Common ones are sessionStorage, localStorage, indexDB, etc
sessionStorage
The life cycle of session storage is page by page, that is, the current session is automatically cleared after closing. The storage capacity is about 5MB, and it is easy to use through the setItem and getItem operations provided by sessionStorage
localStorage
The life cycle of local storage is long-term unless manually cleared. The storage size and storage mode are similar to session
indexDB
IndexDB’s storage life is similar to local’s for a long time, but its storage capacity is unlimited
The end of the
Creation is not easy, thank you for watching!!
Have a great weekend ☕️