Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Context
Scenario 1: One parent component and multiple sub-components. If only the parent component transmits values to the sub-components, only the props value is required
Scenario 2: One parent component and multiple child and grandchild components. You can select Context or Redux to avoid data transfer layer by layer.
Redux: Data storage is usually placed in the outermost layer of the project, so that the data can be examined throughout the project
Context: a component data store in a small scope. When the context changes, the parameters received by the user of the data also change, which is convenient and nice
Step 1: Create the Context object
export const rememberContext=createContext()
Copy the code
Context.Provider is the data Provider. Context.Consumer is the data Consumer
Step 2: Use
Define the provider of the data
< rememberContext Provider value = {{state, dispatch}} > / / component < / rememberContext Provider >Copy the code
User of data (generally not used in hooks)
< mycontext.consumer > {value => /* Render based on the context value */} </ mycontext.consumer >Copy the code
Context, however, is limited in that it only supports one-way data flow. If a child component wants to change the value of its parent component, it needs to use the useReducer
useReducer
UseReducer is an extension of useState and is suitable for handling complex data.
Step 1: Define the stored data
const searchInfoInit={ params1:"", params2:"" } function reducer(){ switch(actions.type){ case "payload": return {... state,... actions.data}; default : return {... state} } } const [state,dispatch]=useReducer(reducer,searchInfoInit)Copy the code
As above: all the data is processed in one place.
Step 2: Create the data provider and the data provided
<rememberContext.Provider value={{state,dispatch}}>
...
</rememberContext.Provider>
Copy the code
Step 3: Deliver data
import {rememberContext} from '.. /context' export default function Child1(){const {state,dispatch}=useContext(rememberContext) return(<div> {state.params1} </div> ) }Copy the code
Step 4: Update sub-components and process data centrally
import {rememberContext} from '.. /context' export default function Child1(){ const {state,dispatch}=useContext(rememberContext) function add(){ Dispatch ({type:'payload', data:{params1:' new '}})} return(<div onClick={add}> parameter 1: {state.params1} </div>)}Copy the code
Such a small range of data storage, very nice ~