zoukankan      html  css  js  c++  java
  • react redux 用法与步骤

    第一步 创建全局的store,并创建对应的reducer规则,使用combineReducers合并多个reducer

    import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
    import createPromiseMiddleware from 'redux-promise-middleware';
    import filterReducer from './routes/Todo/filter/reducer';
    import homeReducer from './routes/Home/reducer';
    const reducer = combineReducers({
      todos: todoReducer,
      filter: filterReducer,
      home: homeReducer
    });
    const middlewares = [createPromiseMiddleware()]; // 这边可以加入其他到中间件 比如thunk logger
    // const middlewares = [logger, thunk];// const win
    = window; const storeEnhancers = compose( applyMiddleware(...middlewares), (win && win.devToolsExtension) ? win.devToolsExtension() : f => f ); const initialState = {}; export default createStore(reducer, initialState, storeEnhancers);

    第二部 在入口js用react-redux提供的provider 包裹, 提供store,用于订阅store变化以及更新全局

    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Provider } from 'react-redux';
    
    import AppIntlProvider from './components/AppIntlProvider';
    import App from './App';
    import store from './Store';
    
    // 未使用 AppIntlProvider 时在此处加载 moment
    // import moment from 'moment';
    // import 'moment/locale/zh-cn';
    // moment.locale('zh-cn');
    
    ReactDOM.render(
      <Provider store={store}>
        {/* <AppIntlProvider> */}
          <App />
        {/* </AppIntlProvider> */}
      </Provider>,
      document.getElementById('root')
    );

    第三部 在你需要用到的页面处 使用react-redux的connect 将action,state 映射到页面到props中

    import React from 'react';
    import { connect } from 'react-redux';
    import {SETID} from './actions;
    class Home extends React.Component { render() {
    return 123 } } const mapDispatchToProps = dispatch => ({ setId: (id) => { dispatch(SETID(id)); }, }); const mapStateToProps = state => ({ data: state.home }); export default connect(mapStateToProps, mapDispatchToProps)(Home);
  • 相关阅读:
    Dapper笔记-Dapper.Common【转】
    ASP.Net Core WebApi几种版本控制对比【转】
    ASP.NET Core WebAPI使用Swagger生成文档
    K8S笔记-Pod介绍【未完成】
    Docker-容器命令
    MySQL笔记-备份命令(mysqldump)
    MySQL笔记-INFORMATION_SCHEMA数据库介绍【转】
    Quartz.net笔记-计划任务触发器(Cron Trigger)
    Quartz.net笔记-简单触发器(Simple Trigger)
    Type序列化器
  • 原文地址:https://www.cnblogs.com/lisiyang/p/12516188.html
Copyright © 2011-2022 走看看