Router state not being persisted in react-native with redux

独自空忆成欢 提交于 2019-12-04 00:29:49

react-native-router-flux doesn't restore a scene by itself even when used with redux. Redux only keeps track of state, so you have to have your app navigate to the previous scene on startup if you want your navigation state to persist.

Assuming you have redux working with react-native-router-flux, all you need to do is connect your app's initial component to redux to get your state and then change your scene to match.

So, in your initial component scene loaded for your app, do something like this at the end to get access to your redux store:

const mapStateToProps = (state) => {
  const { nav } = state

  return {
    currentScene: nav.scene.name,
  }
}

INITIAL_COMPONENT = connect(mapStateToProps)(INITIAL_COMPONENT)

Then in one of your lifecycle methods of that component you could redirect like so:

const { currentScene } = this.props
const initialScene = "Login"

if (currentScene !== initialScene) {
  Actions[currentScene]()
}

You could also pass in props that were used when navigating to the last scene or set a default scene you want to go to if the redux store doesn't have a scene that it's persisting. The app I'm working on is persisting state beautifully now.

You need to create your store like this:

const store = createStore(
  reducers,
  compose(
    applyMiddleware(...middleware),
    autoRehydrate(),
  )
);

The autoRehydrate needs to be part of your compose. Check this compose example.

Can you try this I think what happen is the order of the createStore

const enhancers = compose(
  applyMiddleware(...middleware),
  autoRehydrate(),
);

// Create the store with the (reducer, initialState, compose)
const store = createStore(
  reducers,
  {},
  enhancers
);

Or the other solution should be doing it manually with import {REHYDRATE} from 'redux-persist/constants' and call it inside your reducer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!