react项目之手把手教你如何使用redux,react-redux,redux,redux-thunk,redux-persist,connected-react-router

之前阅读并手写了redux以及react-thunk库的核心功能,那么如何让它们在项目当中使用,这是非常重要的。今天,我们来学习如何在react项目中使用react-redux,redux,redux-thunk,redux-persist,connected-react-router。

首先对上面所提到的库进行安装
npm i react-redux redux redux-thunk redux-persist connected-react-router --save

安装完成之后,在项目src目录新建store文件夹->index.js和history.js,以及store文件夹->reducer文件夹->index.js。
新建store文件夹->history.js代码如下

//新建一个history对象
import {createHashHistory} from 'history';
let history=createHashHistory();
export default history;

reducer文件夹->index.js代码如下

//导出redux合并reducer的api
import {combineReducers} from 'redux';
import {connectRouter} from 'connected-react-router';
import history from '../history';
let reducer=combineReducers({
  router:connectRouter(history)
});
export default reducer;

store文件夹->index.js的代码如下

//导出createStore,applyMiddleware
import {createStore,applyMiddleware} from 'redux';	
import reducer from './reducer';
import thunk from 'redux-thunk';
import history from './history';
import {routerMiddleware} from 'connected-react-router';
import {persistStore,persistReducer} from 'redux-persist';
import storage from 'redux-persist/lib/storage'
const persistConfig={
  key:'root',
  storage
}
const persistedReducer=persistReducer(persistConfig,reducer);
let store=applyMiddleware(thunk,routerMiddleware(history))(createStore)(persistedReducer);
let persistor=persistStore(store);
export{
  store,
  persistor
};

那么入口文件app.js如何使用,代码如下:

import React from 'react';
import {Provider} from 'react-redux';
import {ConnectedRouter} from 'connected-react-router';
import {PersistGate} from 'redux-persist/lib/integration/react';
import {store,persistor} from '../../store';
import history from '../../store/history';
import { Button } from 'antd';
import './App.modules.css';
function App() {
  return (
    <Provider store={store}>
      <PersistGate persistor={persistor}>
        <ConnectedRouter history={history}>
          <Button type="primary">Button</Button>
        </ConnectedRouter>
      </PersistGate>
    </Provider>
  );
}

export default App;

以上就完成了react-redux,redux,redux-thunk,redux-persist,connected-react-router这几个库的综合使用。下面重点介绍一下redux-persist,connected-react-router。
redux-persist:是用来实现实现数据持久化,当用户刷新页面的时候,数据不会丢失并且存在localstorage或者sessionstorage。
connected-react-router:可以通过向仓库派发动作的方式实现路由跳转以及每次路径发生变化时可以把最新的路径放到仓库里面,以便随时在仓库中获取。
好啦~今天的分享就到这里啦。有时间再和你们分享如何实现redux-persist,connected-react-router的核心功能啦。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值