ReactRedux

React-Redux 入门

以下内容来源于 React-Redux官网

使用 React-Redux + Redux-saga 重构 TodoList

  1. 新增 Redux 依赖
  2. 设置 Redux store
  3. 添加 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 连接起来。

文章作者: koral
文章链接: http://luokaiii.github.io/2019/05/10/读书笔记/《React》简书慕课/4.ReactRedux/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自