项目作者: postor

项目描述 :
Persisting React state between route navigation for next.js
高级语言: JavaScript
项目地址: git://github.com/postor/react-persist-state.git
创建时间: 2018-02-06T01:58:55Z
项目社区:https://github.com/postor/react-persist-state

开源协议:

下载


react-persist-state

Persisting React state between route navigation for react SPA | 即使 SPA 页面间跳转仍能使组件保持数据

quick glacne: https://www.youtube.com/watch?v=KfnBAnNu_GI&list=PLM1v95K5B1ntVsYvNJIxgRPppngrO_X4s

usage | 用法

  1. import persist from 'react-persist-state'
  2. const connect = persist({
  3. defaultState: { test: '' }
  4. })
  5. const TestPersist = ({ testProp, setPersist, persisted }) => {
  6. return (<div>
  7. <p>testProp:{JSON.stringify(testProp)}</p>
  8. <p>persisted.test:<input value={persisted.test} onChange={(e) => {
  9. setPersist({ test: e.target.value })
  10. }} /></p>
  11. <p>persisted.test:{JSON.stringify(persisted.test)}</p>
  12. </div>)
  13. }
  14. export default connect(TestPersist)

when you route, persisted will keep | 当你切换页面,persisted

example | 示例

  1. git clone https://github.com/postor/react-persist-state.git
  2. cd react-persist-state/examples/basic
  3. yarn && yarn dev

open http://localhost:3000

params | 参数

persist

pass in config and return connect | 传入配置,并返回 connect

  1. import persist from 'react-persist-state'
  2. const connect = persist({
  3. maxAge: 0, // timeout(miliseconds) for unmounted persist, 0 means no timeout | 超时时间(毫秒),0表示不限
  4. defaultState: {}, // default persisted state | 默认 state
  5. onUpdate: (key, Comp, newState) => {} // use this hook if you need to know each change | 数据更新的钩子
  6. })
  7. // data is stored in memory, if you close browser, data will lost even not reach maxAge

connect

HOC that generates Components can persist | 返回能够保持状态的组件的 HOC

  • Comp the component will need to persist state | Comp 参数为需要保持状态的组件
  • key default is Comp, when you use the same connect and the same Comp multiple times(e.g. list), you need to specify a key for each of the | key 默认为 Comp,如果你使用同一个 connect 多次连接相同的 Comp (例如列表的情况),你需要给每个连接指定一个不同的 key
  1. connect(Comp,key)
  2. [1, 2, 3, 4].map((i) => {
  3. const InputItemK = connect(InputItem, `InputItem-${i}`)
  4. return (<InputItemK key={i} />)
  5. })

props.setPersist

update persisted data | 更新保持的数据

  • obj use as reducer if obj is function, else act like setState in react | 如果是函数,则用作reducer,否则和 react 的 setState 行为一致
  1. const TestPersist = ({ setPersist, persisted }) => {
  2. ...
  3. <a onClick={()=>setPersist(obj)}>

props.persisted

data that persisited | 保持的数据

  1. const TestPersist = ({ setPersist, persisted }) => {
  2. ...
  3. <p>{persisted.something}</p>

clearCache

clear cached data when you need memory efficient | 清理缓存数据

  1. connect.clearCache()