由于 redux 对 UI 的数据响应要用于 store.subscribe(render) 相当不优雅,可以用 react-redux 改善。
react-redux 将所有容器分为 展示组件 和 容器组件
展示组件
负责 UI 显示
先把 index.jsx 显示内容部分提取为一个 component:Container
components/Container.jsx
import { addAction, squareAction } from "../actions/actions";export default function Container(props) {const { num, add, square } = props;return (<div><p>{store.getState()}</p><button onClick={() => addAction(1)}>加1</button><button onClick={() => addAction(2)}>加2</button><button onClick={() => squareAction()}>乘方</button></div>);}
index.jsx 修改为引用 Container 组件
function App() {return <Container></Container>;}
容器组件
Provider
作为一个容器,把组件包裹起来, Provider 传入 store
index.jsx
import React from "react";import ReactDOM from "react-dom";import { Provider } from "react-redux";import { createStore } from "redux";import Container from "./components/Container";import math from "./reducers/math";const store = createStore(math);function App() {return (<Provider store={store}><Container></Container></Provider>);}ReactDOM.render(<App />, document.getElementById("root"));
connect
通过 react-redux 的 connect 方法,借助 Provider 的 props 把 redux 中 store 的 state、dispatch 与 UI 容器的 props 连接一起
components/Container.jsx
import React from "react";import { connect } from "react-redux";import { addAction, squareAction } from "../actions/actions";const mapStateToProps = (state) => {return {num: state,};};const mapDispatchToProps = (dispatch) => {return {add: (value) => dispatch(addAction(value)),square: () => dispatch(squareAction()),};};export default connect(mapStateToProps,mapDispatchToProps)(function Container(props) {const { num, add, square } = props;return (<div><p>{num}</p><button onClick={() => add(1)}>加1</button><button onClick={() => add(2)}>加2</button><button onClick={() => square()}>乘方</button></div>);});
