官网:https://react-redux.js.org/introduction/getting-started
一、Getting Started
1. 安装 React Redux
yarn add react-redux
2. Provider
React Redux 提供了一个 <Provider> 组件,它能让 app 获得 Redux store
import React from 'react'import ReactDOM from 'react-dom'import { Provider } from 'react-redux'import store from './store'import App from './App'const rootElement = document.getElementById('root')ReactDOM.render(<Provider store={store}><App /></Provider>,rootElement)
3. Hooks
React Redux 提供了一对 React hooks 允许 React 组件和 Redux store 做互动
(这两个 hooks 我都不使用,觉得没必要,增加了心智负担)
useSelector 从 store state 读取值并订阅useDispatch 返回 store 的 dispatch 方法让你方便 dispatch action
import React from 'react'import { useSelector, useDispatch } from 'react-redux'import {decrement,increment,incrementByAmount,incrementAsync,selectCount,} from './counterSlice'import styles from './Counter.module.css'export function Counter() {const count = useSelector(selectCount)const dispatch = useDispatch()return (<div><div className={styles.row}><buttonclassName={styles.button}aria-label="Increment value"onClick={() => dispatch(increment())}>+</button><span className={styles.value}>{count}</span><buttonclassName={styles.button}aria-label="Decrement value"onClick={() => dispatch(decrement())}>-</button></div>{/* omit additional rendering output here */}</div>)}
「@浪里淘沙的小法师」
