由于 redux 对 UI 的数据响应要用于 store.subscribe(render) 相当不优雅,可以用 react-redux 改善。

react-redux 将所有容器分为 展示组件 和 容器组件

展示组件

负责 UI 显示
先把 index.jsx 显示内容部分提取为一个 component:Container

components/Container.jsx

  1. import { addAction, squareAction } from "../actions/actions";
  2. export default function Container(props) {
  3. const { num, add, square } = props;
  4. return (
  5. <div>
  6. <p>{store.getState()}</p>
  7. <button onClick={() => addAction(1)}>加1</button>
  8. <button onClick={() => addAction(2)}>加2</button>
  9. <button onClick={() => squareAction()}>乘方</button>
  10. </div>
  11. );
  12. }

index.jsx 修改为引用 Container 组件

  1. function App() {
  2. return <Container></Container>;
  3. }

容器组件

负责管理数据与业务逻辑

Provider

作为一个容器,把组件包裹起来, Provider 传入 store

index.jsx

  1. import React from "react";
  2. import ReactDOM from "react-dom";
  3. import { Provider } from "react-redux";
  4. import { createStore } from "redux";
  5. import Container from "./components/Container";
  6. import math from "./reducers/math";
  7. const store = createStore(math);
  8. function App() {
  9. return (
  10. <Provider store={store}>
  11. <Container></Container>
  12. </Provider>
  13. );
  14. }
  15. ReactDOM.render(<App />, document.getElementById("root"));

connect

通过 react-redux 的 connect 方法,借助 Provider 的 props 把 redux 中 store 的 state、dispatch 与 UI 容器的 props 连接一起

components/Container.jsx

  1. import React from "react";
  2. import { connect } from "react-redux";
  3. import { addAction, squareAction } from "../actions/actions";
  4. const mapStateToProps = (state) => {
  5. return {
  6. num: state,
  7. };
  8. };
  9. const mapDispatchToProps = (dispatch) => {
  10. return {
  11. add: (value) => dispatch(addAction(value)),
  12. square: () => dispatch(squareAction()),
  13. };
  14. };
  15. export default connect(
  16. mapStateToProps,
  17. mapDispatchToProps
  18. )(function Container(props) {
  19. const { num, add, square } = props;
  20. return (
  21. <div>
  22. <p>{num}</p>
  23. <button onClick={() => add(1)}>加1</button>
  24. <button onClick={() => add(2)}>加2</button>
  25. <button onClick={() => square()}>乘方</button>
  26. </div>
  27. );
  28. });