useReducer可配合react-redux方案

接下来 我们来看 useReducer
这个属性 配合 react-redux 就会非常好用

那么 我们编写一段这样代码

import React, {
    
     useState } from 'react';

const ContDom = () => {
    
    
  const [count, setCount] = useState(0);

  return (
    <div>
      cont值{
    
     count }
      <button onClick = {
    
    ()=>{
    
     setCount(count + 1) }}>
        增加
      </button>
      <button onClick = {
    
    ()=>{
    
     setCount(count - 1) }}>
        减少
      </button>
    </div>
  )
}

export default ContDom;

这其实就是实现了一个很基本的 数据 加减功能
我们点增加 cont的值会一直上涨
在这里插入图片描述
反之 点减少 值就会一直向下减
在这里插入图片描述
但如果 我们这个值是react-redux管理的公共数据呢?
由于时间问题 我们直接编写代码如下

import React, {
    
     useReducer } from 'react';

const initialState = {
    
     count: 0 };

const reducer = (state,action) => {
    
    
  switch(action.type){
    
    
    case "incrment":
      return {
    
    count: state.count+1}
    case "decrement":
      return {
    
     count: state.count-1 }
    default:
      return state
  }
}

const ContDom = () => {
    
    
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      cont值{
    
    state && state.count}
      <button onClick = {
    
    ()=>{
    
     dispatch({
    
    type:"incrment"}) }}>
        增加
      </button>
      <button onClick = {
    
    ()=>{
    
     dispatch({
    
    type:"decrement"}) }}>
        减少
      </button>
    </div>
  )
}

export default ContDom;

我们通过这里写的这个reducer来模仿redux操作
在这里插入图片描述
我们的基本功能也都实现了

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/131370048
今日推荐