Redux

  -  
This commit does not belong to any branch on this repository, and may belong khổng lồ a fork outside of the repository.

Bạn đang xem: Redux


*

*
*
*

October 15th, 2021 - Move sầu khổng lồ TypeScript (Thanks
ckalika) spoke with
rt2zz about taking over maintenance of the project, and we agreed to give it a shot & see how we go. My priorities are as follows:

Go through and triage the existing issues

Separate them into lớn bugs, feature requests, basic questions/requests for code samples, và issues that are either not project-specific or don"t fall within the remit of the project (specific definitions & criteria will be posted in the future)Determine the severity/urgency of each bug or feature requestGuestimate the kích cỡ of themDetermine which are actionable immediately or in the short termEstablish some semblance of kiểm tra criteria for each

Upgrade dependencies (where possible) so that we"ve sầu got something building with modern versions

Note: Right now, it"s about modernising the project infrastructure & build process without making breaking API changes

Go through the existing pull requests

Merge the ones that deal with documentation, code samples, etc.Đánh Giá and merge the ones that khuyễn mãi giảm giá with open issuesnhận xét & merge the ones that will require breaking changes and consult authors about redux-persist
react-native-async-storage/async-storage";const persistConfig = //... storage: AsyncStorage

Quickstart

npm install redux-persist

Usage Examples:

Code Splitting

Basic UsageBasic usage involves adding persistReducer và persistStore to lớn your cài đặt. IMPORTANT Every app needs to decide how many levels of state they want to "merge". The default is 1 level. Please read through the state reconciler docs for more information.


let store = createStore(persistedReducer) let persistor = persistStore(store) return store, persistor ">

// configureStore.jsimport createStore from "redux"import persistStore, persistReducer from "redux-persist"import storage from "redux-persist/lib/storage" // defaults khổng lồ localStorage for webimport rootReducer from "./reducers"const persistConfig = key: "root", storage,const persistedReducer = persistReducer(persistConfig, rootReducer)export mặc định () => let store = createStore(persistedReducer) let persistor = persistStore(store) return store, persistor
If you are using react, wrap your root component with PersistGate. This delays the rendering of your app"s UI until your persisted state has been retrieved và saved khổng lồ redux. NOTE the PersistGate loading prop can be null, or any react instance, e.g. loading=


return ( );;">

import PersistGate from "redux-persist/integration/react"https:// ... normal setup, create store & persistor, import components etc.const App = () => return ( Provider store=store> PersistGate loading=null persistor=persistor> RootComponent /> /PersistGate> /Provider> );;

API

Full API

persistReducer(config, reducer)argumentsconfig objectrequired config: key, storagenotable other config: whitelist, blackmenu, version, stateReconciler, debugreducer functionany reducer will work, typically this would be the top cấp độ reducer returned by combineReducersreturns an enhanced reducerpersistStore(store, )argumentsstore redux store The store to lớn be persisted.config object (typically null)If you want khổng lồ avoid that the persistence starts immediately after calling persistStore, mix the option manualPersist. Example: manualPersist: true Persistence can then be started at any point with persistor.persist(). You usually want khổng lồ vì this if your storage is not ready when the persistStore điện thoại tư vấn is made.callback function will be called after rehydration is finished.returns persistor objectpersistor objectthe persistor object is returned by persistStore with the following methods:.purge()purges state from disk và returns a promise.flush()immediately writes all pending state khổng lồ disk và returns a promise.pause()pauses persistence.persist()resumes persistence

State Reconciler

State reconcilers define how incoming state is merged in with initial state. It is critical khổng lồ choose the right state reconciler for your state. There are three options that ship out of the box, let"s look at how each operates:

hardSet (import hardSet from "redux-persist/lib/stateReconciler/hardSet")This will hard set incoming state. This can be desirable in some cases where persistReducer is nested deeper in your reducer tree, or if you vì not rely on initialState in your reducer.incoming state: foo: incomingFoo initial state: foo: initialFoo, bar: initialBar reconciled state: foo: incomingFoo // note bar has been droppedautoMergeLevel1 (default)This will tự động merge one level deep. Auto merge means if the some piece of substate was modified by your reducer during the REHYDRATE action, it will skip this piece of state. Level 1 means it will shallow merge 1 level deep.incoming state: foo: incomingFoo initial state: foo: initialFoo, bar: initialBar reconciled state: foo: incomingFoo, bar: initialBar // note incomingFoo overwrites initialFooautoMergeLevel2 (import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2")This acts just lượt thích autoMergeLevel1, except it shallow merges two levelsincoming state: foo: incomingFoo initial state: foo: initialFoo, bar: initialBar reconciled state: foo: mergedFoo, bar: initialBar // note: initialFoo and incomingFoo are shallow merged

Example
import hardSet from "redux-persist/lib/stateReconciler/hardSet"const persistConfig = key: "root", storage, stateReconciler: hardSet,

React Integration

Redux persist ships with react integration as a convenience. The PersistGate component is the recommended way khổng lồ delay rendering until persistence is complete. It works in one of two modes:

loading prop: The provided loading value will be rendered until persistence is complete at which point children will be rendered.function children: The function will be invoked with a single bootstrapped argument. When bootstrapped is true, persistence is complete và it is safe khổng lồ render the full phầm mềm. This can be useful for adding transition animations.

Blackcác mục & Whitelist

By Example:


// BLACKLISTconst persistConfig = key: "root", storage: storage, blacklist: <"navigation"> // navigation will not be persisted;// WHITELISTconst persistConfig = key: "root", storage: storage, whitelist: <"navigation"> // only navigation will be persisted;

Nested Persists

Nested persist can be useful for including different storage adapters, code splitting, or deep filtering. For example while blackmenu & whitecác mục only work one màn chơi deep, but we can use a nested persist lớn blackmenu a deeper value:


import combineReducers from "redux"import persistReducer from "redux-persist"import storage from "redux-persist/lib/storage"import authReducer, otherReducer from "./reducers"const rootPersistConfig = key: "root", storage: storage, blacklist: <"auth">const authPersistConfig = key: "auth", storage: storage, blacklist: <"somethingTemporary">const rootReducer = combineReducers( auth: persistReducer(authPersistConfig, authReducer), other: otherReducer,)export mặc định persistReducer(rootPersistConfig, rootReducer)

Migrations

persistReducer has a general purpose "migrate" config which will be called after getting stored state but before actually reconciling with the reducer. It can be any function which takes state as an argument & returns a promise to lớn return a new state object.

Xem thêm: Hướng Dẫn Sửa Lỗi Không Gõ Được Tiếng Việt Trên Cốc Cốc Bản Mới Nhất 2020

Redux Persist ships with createMigrate, which helps create a synchronous migration for moving from any version of stored state lớn the current state version.

Transforms

Transforms allow you to lớn customize the state object that gets persisted and rehydrated.

There are several libraries that tackle some comtháng implementations for transforms.

When the state object gets persisted, it first gets serialized with JSON.stringify(). If parts of your state object are not mappable to JSON objects, the serialization process may transkhung these parts of your state in unexpected ways. For example, the javascript Set type does not exist in JSON. When you try lớn serialize a Set via JSON.stringify(), it gets converted khổng lồ an empty object. Probably not what you want.

Below is a Transform that successfully persists a Set property, which simply converts it khổng lồ an array and back. In this way, the Set gets converted lớn an Array, which is a recognized data structure in JSON. When pulled out of the persisted store, the array gets converted bachồng to a Set before being saved to the redux store.


// convert mySet to an Array. return ...inboundState, mySet: <...inboundState.mySet> ; , // transform state being rehydrated (outboundState, key) => // convert mySet bachồng to a Set. return ...outboundState, mySet: new Set(outboundState.mySet) ; , // define which reducers this transkhung gets called for. whitelist: <"someReducer"> );export default SetTransform;">

import createTransform from "redux-persist";const SetTransform = createTransform( // transform state on its way khổng lồ being serialized and persisted. (inboundState, key) => // convert mySet khổng lồ an Array. return ...inboundState, mySet: <...inboundState.mySet> ; , // transkhung state being rehydrated (outboundState, key) => // convert mySet baông xã lớn a Set. return ...outboundState, mySet: new Set(outboundState.mySet) ; , // define which reducers this transkhung gets called for. whitelist: <"someReducer"> );export default SetTransform;
The createTranssize function takes three parameters.

An "inbound" function that gets called right before state is persisted (optional).An "outbound" function that gets called right before state is rehydrated (optional).A config object that determines which keys in your state will be transformed (by mặc định no keys are transformed).

Xem thêm: Nopat Là Gì - Net Operating Profit After Tax (Nopat) Là Gì

In order to lớn take effect transforms need khổng lồ be added to lớn a PersistReducer’s config object.


import storage from "redux-persist/lib/storage";import SetTranskhung from "./transforms";const persistConfig = key: "root", storage: storage, transforms: ;