zoukankan      html  css  js  c++  java
  • react-hooks简单同步异步处理小技巧

    import React, { useState, useEffect, useReducer } from 'react';
    import { useImmer } from "use-immer"
    import './App.css';
    
    
    function reducer(state: { count: number; }, action: { type: any; }) {
      switch (action.type) {
        case 'increment':
          return { count: state.count + 1 };
        case 'decrement':
          return { count: state.count - 1 };
        default:
          throw new Error();
      }
    }
    
    function App() {
      // 定义
      const [state, setState] = useImmer({
        people: [
          {
            name: '马云',
            englishName: 'Jack Ma'
          },
          {
            name: '马化腾',
            englishName: 'Pony Ma'
          },
          {
            name: '李彦宏',
            englishName: 'Robin Li'
          }
        ]
      })
    
      const [num, setNum] = useState(1);
    
      const [stateReducer, dispatchReducer] = useReducer(reducer, {count:999});
      useEffect(() => {
        console.log(num);
        //处理异步数据
      }, [num])
    
      useEffect(() => {
        console.log(state);
      }, [state.people[2]])
    
      const onClick = () => {
        setNum((num) => {
          console.log(num,"点击之前的变化");
          //处理异步数据
          return num = 2
        })
      }
      const onClick1 = () => {
        setState((state: { people: { name: string; }[]; }) => { state.people[2].name = '陈强' })
        console.log(state);//异步
      }
      const onClick2 = () => {
        dispatchReducer({ type:"increment"})
        console.log(stateReducer.count);//异步
      }
      return (
        <div className="App">
          <h1>我是useReducer----{stateReducer.count}</h1>
          <h1>{num}</h1>
          <ul>
            {state.people.map(item => <li key={item.englishName}>{item.name}</li>)}
          </ul>
          <button onClick={onClick}>点击</button>
          <button onClick={onClick1}>复杂数据处理</button>
    
          <button onClick={onClick2}>我要修改stateReducer</button>
        </div>
      );
    }
    
    export default App;
    

      

  • 相关阅读:
    go语言和c++比较
    追逐光和影,成就风与电
    vue中使用mockjs
    JS 实现关键字文本搜索 高亮显示
    vue将页面(dom元素)转换成图片
    js复制功能(pc复制,移动端复制到手机剪切板)
    Django终端打印SQL语句
    Oracle查看表空间及大小
    Oracle 五种约束的创建和移除:
    Oracle的decimal和number的对比
  • 原文地址:https://www.cnblogs.com/cq1715584439/p/12674689.html
Copyright © 2011-2022 走看看