用 use reducer 代替 redux的方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import React, { useReducer } from 'react'


const Child1 = (props)=> {
  console.log(props)
  
  return (
    <div>
      child@!!! <br /> 
      <button onClick={()=>props?.callback('add') } >add</button>
      <button onClick={()=> props?.callback('sub') } >sub</button>
    </div>
  )
}

export default function ReducerDemo() {

  const [cnt ,dispatch ] = useReducer((state,type) => {
    console.log(state,type)
    switch(type) {
      case 'add': return state + 1
      case 'sub': return state - 1
      default : return state*2
    }
    return 0
  },0)
  //第二个参数表示默认值, 和 useState 很像的



  
  return (
    <div>
      hello reducer 
      cnt := {cnt}

      <Child1 callback={dispatch} />
    </div>
  )

}

实例 demo 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import React, { useReducer } from 'react'


const Child1 = (props)=> {
  console.log(props)
  
  return (
    <div>
      child@!!! <br /> 
      <button onClick={()=>props?.callback({type:'add',current:'button'}) } >add</button>
      <button onClick={()=> props?.callback({
        type:'sub',
        current:'button2'
      }) } >sub</button>
    </div>
  )
}

export default function ReducerDemo() {

  const [cnt ,dispatch ] = useReducer((state,payload) => {
    console.log(state,payload)
    switch(payload?.type) {
      case 'add': return state + 1
      case 'sub': return state - 1
      default : return state*2
    }
    return 0
  },0)
  //第二个参数表示默认值, 和 useState 很像的



  
  return (
    <div>
      hello reducer 
      cnt := {cnt}

      <Child1 callback={dispatch} />
    </div>
  )

}

使用 useReducer 代替 redux的案例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import React, { useReducer } from 'react'

const Table = (props)=> {
  return (
    <div>
      table: current = {props?.page}
    </div>
  )
}
const Pagination = (props) => {
  let pags = [1,2,3]
  let clicked = props.callback||props.dispatch
  return (
    <div>
      pagination : 
      {
        pags.map(cur => {
          return (
            <button key={cur} onClick={()=>clicked && clicked({
              page:cur
            })} >{cur}</button>
          )
        })
      }
      
      
      ; 当前页数 = {props?.page}
    </div>
  )
}

export default function ReducerDemo() {

  const [page ,setPage ] = useReducer((state,payload) => {
    console.log(state,payload)
    return payload.page||state
  },1)

  
  return (
    <div>
      <Table page={page} />
      <Pagination dispatch={setPage} page={page} />
        
    </div>
  )

}