React+Redux

1.Redux

import { createStore, combineReducers } from 'redux';
import { composeWithDevTools } from "redux-devtools-extension";
// Redux 提供了一个combineReducers方法,用于 Reducer 的拆分。你只要定义各个子 Reducer 函数,然后用这个方法,将它们合成一个大的 Reducer。
// 多个对象可以用 combineReducers 进行整合
const reducer = combineReducers({
	source:Source
	token:Token
   // key:value 的形式
});
// 引入createStore,专门用于创建redux中最为核心的store对象
const store = createStore(reducer, composeWithDevTools())
//观察者
store.subscribe(() => {
});
export default store;

Redux-thunk中间件(支持异步)

import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
 const store = createStore(
  reducers, 
  applyMiddleware(thunk)
);

export const getApi = () => {
  // 这里可以接收 dispatch 参数,直接使用,相当于调用 store.dispatch 方法
  return (dispatch) => {
    axios.get('/api')
      .then((res) => {
        const data = res.data
        const action = getInitListAction(data)
        dispatch(action)
      })
      .catch((error) => {
        console.log(error)
      })
  }
}
componentDidMount() {
   const action = getApi ()
   store.dispatch(action)
} 

redux-persist

//引入createStore,专门用于创建redux中最为核心的store对象
import { createStore } from 'redux'
import {persistStore, persistReducer} from 'redux-persist'
import storage from 'redux-persist/lib/storage'
//引入汇总之后的reducer
import reducers from './reducers'
 
import loading from '../redux/reducers/loading'
 
//在localStorge中生成key为root的值
const persistConfig = {
  key: 'root',
  storage,
  blacklist:['loading'],  //设置某个reducer数据不持久化,
  whitelist: ['user'] // 白名单 只存白名单列表里的  黑名单 除了黑名单列表 其他都存
}
 
const myPersistReducer = persistReducer(persistConfig, reducers)
 
const store = createStore(myPersistReducer)
 
const persistor = persistStore(store)
 
export {
  store,
  persistor
}

react-redux

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import "antd/dist/antd.css";
import "./i18n/configs";
import { Provider } from "react-redux";
import rootStore from "./redux/store";
import axios from "axios";
import { PersistGate } from "redux-persist/integration/react";

axios.defaults.headers["x-icode"] = "FB80558A73FA658E";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={rootStore.store}>
      <PersistGate persistor={rootStore.persistor}>
        <App />
      </PersistGate>
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

import {connect} from 'react-redux'

const mapStateToProps = (state) => {
  return {
     topicList: state.getIn(['home', 'topicList'])
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getTopicList() {
      dispatch(getTopicList());
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Header);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值