要将store注入到组件当中,必须用标签将组件包裹
组件引入自"react-redux"核心包import { Provider } from 'react-redux'; import store from './store/index'; <Provider store={ store}> <App /> </Provider>
- "react-redux"核心包为我们提供的钩子函数
- ①useSelector(state => {}) 用来抓取store中存储的state数据
1.其中形参state获取的是所有切片中的state集合
2.函数中通过返回 state.name (name为store中各切片的属性名),来提取各切片数据
3.此时,调用useSelector()函数会返回回调函数中的返回值,用一个变量接收该对象即可
②useDispatch()获取派发器对象,此钩子函数无需传参const student = useSelector(state => state.student) console.log(student.age);
引入切片页面中暴露的action创建器(例如setName、setAge等),然后作为调用dispatch时的参数即可import { useDispatch } from "react-redux"; const dispatch = useDispatch()
import {
setName,setAge } from "./store";
const nameHandler = () => {
dispatch(setName({
name:'杨玉蝉'}))
}