react - 19. redux-persist 的使用

访问量: 172

参考: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 ,或者 )

订阅/RSS Feed

Subscribe

分类/category