很简单的界面
加减按钮,和一个显示state.count的标签
无论怎么改都获取不到dispatch方法,点加号总是显示undefined
首先这是我写的reducer
const initState ={
count:0
}
const countreducer =(prestate=initState,action)=>{
const {type,data} =action
switch(type){
case 'increment':
return prestate.count + data;
case 'decrement':
return prestate.count -data;
default:
return prestate
}
}
export default countreducer
//初始了一个count
这是store
import { createStore } from "redux";
import countreducer from "./countreducer"
const store = createStore(countreducer)
export default store
这是Count组件的界面
import React from "react";
import{Button} from 'antd'
import { useSelector,useDispatch } from "react-redux";
//hooks使用redux与类组件的区别
export default function Count ({action}){
const number =useSelector(state => state.count)
//state不需要用connect组件获取
const dispatch = useDispatch()
//dispatch也不需要用connect获取
const increment =(dispatch)=>{
dispatch({type:"increment",data:1})
console.log(number)
}
const decrement=()=>{}
return(
<>
<h1> {number}</h1>
<Button onClick={increment}>+</Button>
<Button onClick={decrement}>-</Button>
</>
)
}
store数据我已经通过Provider组件共享给组件了
你打印 dispatch 是一个函数 吗? 有值吗!?