react——useState和useReducer

       Both useState and useReducer are used to store and update state, which is an upgraded version of useReducerstate management . useStateuseReducer can store variables externally to implement asynchronous operations. To achieve cross-component communication, it needs to be implemented in combination with useContext

1. Principle:

二、useState

(1) Grammar

1. Format:

        const [state,setState] = useState(initState)

2. Rendering

        Get variable value through state

        Modify variable value through setState

(2) Case - Realize addition and subtraction

import React ,{useState}from 'react'

export default function App() {
    const [count,setCount] = useState(1)
  return (
    <div>
      <button onClick={()=>{
        setCount(count+1)
      }}>加一</button>
        <div>{count}</div>
        <button onClick={()=>{
           setCount(count-1)
        }}>减一</button>
    </div>
  )
}

三、useReduce

 (1) Grammar

1. Define external data and methods

Data : Define the initial value data in the data

const initState = {//外部对象,里面是初始值
  count: 0
}

Method : Do logic processing, with two parameters

        The method of accepting and dispatching through action, combined with switch to do logical processing correspondingly

        Get external initial value data through prevState

const reduce = (prevState, action) => {//处理函数
  // prevState拿到的外部对象数据
  // action获取到dispatch传来的对象
 
}

2, quote useReducer

// 格式
const [state, dispatch] = useReducer(reduce, initState)

3. Rendering

        Get the value through the state. variable

        Dispatch events to the outside through dispacth

<button onClick={() => {
   dispatch({
      type: 'add'
    })
 }}>加一</button>
 {/* 通过 state.变量来获取初始值*/}
 <div>{state.count}</div>
 <button onClick={() => {
    dispatch({
      type: "reduce"
     })
 }}>减一</button>
   

(2) Case

Realize an accumulation and subtraction function

import React, { useReducer } from 'react'

const reduce = (prevState, action) => {//处理函数
  // prevState拿到的外部对象数据
  // action获取到dispatch传来的对象
  let newState = { ...prevState }// 不能影响老数据,深拷贝一次
  switch (action.type) {
    case "reduce":
      newState.count--;
      return newState
    case "add":
      newState.count++;
      return newState
    default :
      return prevState
  }

}
const initState = {//外部对象,里面是初始值
  count: 0
}
export default function App() {
  // 格式
  const [state, dispatch] = useReducer(reduce, initState)
  return (
    <div>
      {/* 通过 dispatch派发事件*/}
      <button onClick={() => {
        dispatch({
          type: 'add'
        })
      }}>加一</button>
      {/* 通过 state.变量来获取初始值*/}
      <div>{state.count}</div>
      <button onClick={() => {
        dispatch({
          type: "reduce"
        })
      }}>减一</button>
    </div>
  )
}

Four, useState and useReducer realize cross-component communication

        The two implementations of cross-component communication need to be implemented in combination with useContext

(一)useState+useContext

import React, { useState, useContext } from 'react'
// 1、全局定义context对象
const GlobalContext = React.createContext()
export default function App() {
    const [num, setNum] = useState(0)
    return (
        // 一定要为父标签,作为唯一的根标签
        <GlobalContext.Provider value={
   
   {
            num: num,//传递过去的值
            changeNum: (value) => {
                setNum(num + 1)
            }
        }}>

            <Sub1 />

        </GlobalContext.Provider>
    )
}
function Sub1() {
    const value = useContext(GlobalContext)
    console.log(value);
    const addFn = (value) => {
        value.changeNum()
    }
    return (
        <div>
            <div>生产者提供的值:{value.num}</div>
            <button onClick={() => addFn(value)}>加一</button>
        </div>
    )
}

 

(二)useReducer+useContext

import React, { useReducer, useContext } from 'react'
// 1、全局定义context对象
const GlobalContext = React.createContext()
// 外部方法

const reduce = (prevState, action) => {
    const newState = {...prevState}
    console.log(prevState, action);
    switch (action.type) {
        case "add":
            newState.num++
            return newState
        case "jian":
            newState.num--
            return newState
        default:
            return prevState

    }

}

// 外部数据
const initState = {
    num: 0
}

export default function App() {
    const [state, dispacth] = useReducer(reduce, initState)
    return (
        // 一定要为父标签,作为唯一的根标签
        <GlobalContext.Provider value={
   
   {
            state,//传递过去的值-对象
            dispacth
        }}>

            <Sub1 />

        </GlobalContext.Provider>
    )
}
function Sub1() {
    const {state,dispacth} = useContext(GlobalContext)
 
    const addFn = (dispacth) => {
        dispacth({
            type: "add"
            // value:"11"可以带一个变量过去
        })
    }
    const jianFn = (dispacth) => {
        dispacth({
            type: "jian"
            // value:"11"可以带一个变量过去
        })
    }
    return (
        <div>
            <div>生产者提供的值:{state.num}</div>
            <button onClick={() => addFn(dispacth)}>加一</button>
            <button onClick={() => jianFn(dispacth)}>减一</button>
        </div>
    )
}

 

Guess you like

Origin blog.csdn.net/m0_55173487/article/details/128547923