hooks (useContext+useReducer) realize global state management

A globally shared state should not only be shared or transmitted, but it should also be able to be modified, making one modification and changing everywhere. Next, we will improve the Liezi on the official website to realize status sharing and modification.

First picture:
Insert picture description here

App.js

import React,{useEffect,useReducer,useState} from 'react';
// import logo from './logo.svg';
import './App.css';
import {
  // BrowserRouter as Router,
  Route,
  Link,
  // Router
} from "react-router-dom";
import {initState,context,countReducer} from './reducer/index'
import Count from './components/Count'
import ShowCount from './components/ShowCount'



function App() {
	let store=useReducer(countReducer,initState)
	useEffect(()=>{
		console.log('store',store)
	})
	let linkArr=[
		{
			path:'/page1',
			label:'页面1'
		},
		{
			path:'/page2',
			label:'页面2'
		},
		{
			path:'/page3',
			label:'页面3'
		}
	]
	let [currentIndex,setCurrentIndex]=useState(0)
	function changeCurrentIndex(index){
		setCurrentIndex(index)
	}
  return (
    <context.Provider value={store}>
		<div className="App">
			<ul className="list">
				{
					linkArr.map((item,index)=>{
						return <li className="list-item" onClick={(e)=>changeCurrentIndex(index,e)} key={index}><Link to={item.path} className={`${index===currentIndex?'active':''}`}>{item.label}</Link></li>
					})
				}
			</ul>
			<Route path='/page1' component={Page1}></Route>
			<Route path='/page2' component={Page2}></Route>
			<Route path='/page3' component={Page3}></Route>
		</div>
    </context.Provider>
  );
}

function Page1(){
	return (
		<div>
			<Count></Count>
		</div>
	)
}
function Page2(){
	return (
		<div>
			<ShowCount></ShowCount>
		</div>
	)
}
function Page3(){
	return (
		<div>
			this is  page3
		</div>
	)
}
export default App;

The main function of app.js: Use context.Provider at the top-level component, and share the only store (including state, and dispatch) with the components below. Any of the components below get state and dispatch through useContext, and then they can share and change the state. value. How to get the state and dispatch we need is obtained through useReducer.

./reducer/index

import React from 'react'
let initState={
    count:0
}
function countReducer(state={},action){
    switch(action.type){
        case 'increment':
            return {count:state.count+1}
        case 'decrement':
            return {count:state.count-1 }
        default:
            return state
    }
}
let context =React.createContext()
export {
    countReducer,
    initState,
    context
}

This includes the reducer and iniState, and also exports the context. Everyone that uses the shared state needs to use this context to ensure that all components use the same context.

Count.js

import React,{useContext} from 'react'
import {context} from '../reducer/index'
function  Count(){
    let [state,dispatch]=useContext(context)
    return (
        <div>
           <h1>count:{state.count}</h1>
           <div>
            <button style={
   
   {width:'128px',height:'30px'}} onClick={()=>dispatch({type:'decrement'})}>-</button>
            <button style={
   
   {width:'128px',height:'30px'}} onClick={()=>dispatch({type:'increment'})}>+</button>
           </div>
        </div>
    )
}
export default Count

The main function of count.js: get state and dispatch through useContext to display and modify state.

ShowCount.js

import React,{useContext} from 'react'
import {context} from '../reducer/index'

function ShowCount(){
    let [state]=useContext(context)
    return (
        <div>
           <h1>count:{state.count}</h1>
        </div>
    )
}
export default ShowCount

showCount.js is similar to count.js. Only state is used here.

Guess you like

Origin blog.csdn.net/weixin_44494811/article/details/107750646