官网:https://react-redux.js.org/introduction/getting-started

一、Getting Started

1. 安装 React Redux

  1. yarn add react-redux

2. Provider

React Redux 提供了一个 <Provider> 组件,它能让 app 获得 Redux store

  1. import React from 'react'
  2. import ReactDOM from 'react-dom'
  3. import { Provider } from 'react-redux'
  4. import store from './store'
  5. import App from './App'
  6. const rootElement = document.getElementById('root')
  7. ReactDOM.render(
  8. <Provider store={store}>
  9. <App />
  10. </Provider>,
  11. rootElement
  12. )

3. Hooks

React Redux 提供了一对 React hooks 允许 React 组件和 Redux store 做互动
(这两个 hooks 我都不使用,觉得没必要,增加了心智负担)

useSelector 从 store state 读取值并订阅
useDispatch 返回 store 的 dispatch 方法让你方便 dispatch action

  1. import React from 'react'
  2. import { useSelector, useDispatch } from 'react-redux'
  3. import {
  4. decrement,
  5. increment,
  6. incrementByAmount,
  7. incrementAsync,
  8. selectCount,
  9. } from './counterSlice'
  10. import styles from './Counter.module.css'
  11. export function Counter() {
  12. const count = useSelector(selectCount)
  13. const dispatch = useDispatch()
  14. return (
  15. <div>
  16. <div className={styles.row}>
  17. <button
  18. className={styles.button}
  19. aria-label="Increment value"
  20. onClick={() => dispatch(increment())}
  21. >
  22. +
  23. </button>
  24. <span className={styles.value}>{count}</span>
  25. <button
  26. className={styles.button}
  27. aria-label="Decrement value"
  28. onClick={() => dispatch(decrement())}
  29. >
  30. -
  31. </button>
  32. </div>
  33. {/* omit additional rendering output here */}
  34. </div>
  35. )
  36. }

「@浪里淘沙的小法师」