react - 19. redux-persist 的使用

栏目: 服务器 · 发布时间: 5年前

内容简介:参考:react native 中几乎绝大部分操作都是异步的,包括 读取本地存储。

参考: https://github.com/rt2zz/redux-persist 和 

https://github.com/rt2zz/redux-persist/blob/master/docs/PersistGate.md

react native 中几乎绝大部分操作都是异步的,包括 读取本地存储。

而现实页面则是同步的,而且貌似没有特别容易的办法 让页面跟 读取后的数据同步(自动刷新)

redux-persis 项目就是为了这个目的而生的。

示范代码已经上传: https://github.com/sg552/demo_redux_with_async_storage.git

1. 安装

$ npm install redux-persist --save

并根据文档: http://siwei.me/blog/posts/react-15-redux 建立一个空白的redux项目。

2. 修改store.js  (注意名字和路径跟官方文档略有不同)

import {createStore, combineReducers } from 'redux'
import countReducer from './reducers'

// persist store
import {persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage'

const rootReducer = combineReducers({
  countReducer: countReducer
})

const myReducer = persistReducer({
  key: 'root',
  storage
}, rootReducer)

export default () => {
  let store = createStore(myReducer)
  let persistor = persistStore(store)
  return { store , persistor}
}

3. 修改index.js

/** @format */

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

// 以下为 为调用Redux 而新增的代码
// 这句话虽然没有被显示调用,但是不加会报错, 在 const myProvider那里。
import React from 'react'
import { Provider } from 'react-redux'
import configureStore from './store'

// 导入redux-persist
import {PersistGate} from 'redux-persist/integration/react'

const {store, persistor}  = configureStore()

const onBeforeLift = () => {

}

const myProvider = () => {
  return (
    <Provider store = {store}>
      <PersistGate loading={null} persistor={persistor}
        onBeforeLift={onBeforeLift}
      >
        <App />
      </PersistGate>
    </Provider>
  )
}

AppRegistry.registerComponent(appName, () => myProvider);

4. 其他代码同 普通的 redux 项目(见DEMO ,或者 )


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

冷启动

冷启动

高臻臻 / 人民邮电出版社 / 2018-5 / 59.80元

本书针对中小企业做营销没预算、没用户的痛点,系统梳理冷启动项目的思维和策略,帮助营销和运营人员实现项目从0到1再到n的爆发式增长。 全书有两条主线。一条是营销思维线,侧重于如何思考,包括:升级行业、创新文化,寻找营销切入点;挖掘品 牌和个人的亮点、“做轻”产品,打造具有互联网营销特色的冷启动项目;突破思维,把实体经济“做虚”,发挥虚拟经济的价值。另一条是营销策略线,侧重于如何行动,包......一起来看看 《冷启动》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具