React-Redux 入门
以下内容来源于
使用 React-Redux + Redux-saga 重构 TodoList
- 新增 Redux 依赖
- 设置 Redux store
- 添加 React-Redux 依赖
一、使用 Provider 标签
React Redux 提供了 <Provider/>
标签,使 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
);
二、组件连接 Store
React Redux 提供了 connect 将组件连接到 store。
import { connect } from "react-redux";
import { increment, decrement, reset } from "./actionCreators";
// const Counter = ...
const mapStateToProps = (state /*, ownProps*/index.html) => {
return {
counter: state.counter
};
};
const mapDispatchToProps = { increment, decrement, reset };
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
三、拆分 Reducer.js
当 Reducer 中需要接收的 action 过多,且各个组件都有自己的 action、reducer、constants 时,可以将 reducer.js 分散到各个组件模块中。在总的 reducer 中使用 combineReducers ,将各个子 reducer 连接起来。