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);
  • 相关阅读:
    转:我们是否应该把后端构建为API
    转:浅谈命令查询职责分离(CQRS)模式
    转:如何在Linux上提高文本的搜索效率
    结对编程???该歇歇了
    码农语录•「程序代码的可信度,不会比写的人还可信。」
    七个错误可能引发网页布局灾难
    为什么我不再和别人比较了?
    顶级程序员的10条最佳实践
    程序员淡定的姿态和操蛋的心...
    【好文翻译】码农们:效率与质量,你选择哪个?
  • 原文地址:https://www.cnblogs.com/lisiyang/p/12516188.html
Copyright © 2011-2022 走看看