其他分享
首页 > 其他分享> > React redux 存值取值 持久化

React redux 存值取值 持久化

作者:互联网

先创建一个store.js文件
在https://www.npmjs.com/package/redux-persist官网里面

import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web

import rootReducer from './reducers'

const persistConfig = {
  key: 'root',
  storage,
  whitelist: ['token']
}

const persistedReducer = persistReducer(persistConfig, rootReducer)
let store = createStore(persistedReducer)
let persistor = persistStore(store)
export default { store, persistor }

在你的index.js里面继续引入

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

上面sotre.js抛出 现在解构引用

import storefn from './store'
const { store, persistor}=storefn

常规设置,创建存储和持久性,导入组件等。

 <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <ConfigProvider locale={zhCN}>
        <App />
      </ConfigProvider>
    </PersistGate>
  </Provider>

去建立一个reducers文件
新建一个token.js

var token = localStorage.getItem('data')
function token(state = token, { type, payload }) {
  switch (type) {
    case 'typeName':
      localStorage.setItem('data', payload)
      return payload
    default:
      return state
  }
}

export default token

建立一个index.js 挂载

import { combineReducers } from 'redux'
import token from './token'
export default combineReducers({
  token
})

可以在http.js里面看看能不能输出

config.data.token = store.getState().token

在你的页面连结仓库

import { connect } from 'react-redux'
export default connect((state) => {
  return {
    token: state.token
  }
}, {
  setName(text) {
    return {
      type: "see",
      payload: text
    }
  }
})(页面)

页面存值

 props.setName(存值)

页面取值

{props.token}

完成了React redux 存值取值 持久化

标签:persistor,js,React,token,存值,import,redux,store
来源: https://blog.csdn.net/weixin_47353884/article/details/114728526