【问题标题】:react redux-persist with routes将 redux-persist 与路由反应
【发布时间】:2017-11-15 16:56:00
【问题描述】:

我正在使用 redux-persist 的反应,并且如果用户从 /home 转到 /search,“Rehydrate”事件会被触发两次。

所以首先状态在根中是正确的。然后我改变我的搜索参数。点击搜索后,我可以看到“Rehydrate”事件被激活,它再次改变了应用程序的状态。

知道出了什么问题以及我能做些什么来解决它吗?

这是我正在使用的代码

import {Router, Route, browserHistory, Redirect} from 'react-router';
import {persistStore, autoRehydrate} from 'redux-persist'
import {Provider} from 'react-redux';
import {compose,createStore, applyMiddleware} from 'redux';
import reducers from './reducers';
import thunkMiddleware  from 'redux-thunk';
import promiseMiddleware from 'redux-promise-middleware';
import localForage from "localforage";


export const store = createStore(
    reducers,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
    compose(
        applyMiddleware(
            thunkMiddleware,
            promiseMiddleware()),
        autoRehydrate()
    )
);
const persistor = persistStore(store, {storage: localForage});
render(
    <Provider store={store} persistor={persistor}>
        <Router history={browserHistory}>
            <Route path="/" component={Home}/>
            <Route path="/search" component={Search}/>
        </Router>
    </Provider>,
    document.getElementById('root')
);

感谢和问候

PS:附上redux状态的图片。正如您在触发搜索后看到的那样,有一个新的 persist/Rehydrate 事件。我有点幸运,在补水事件之后搜索仍然完成 - 但行为并不好。

【问题讨论】:

    标签: reactjs redux persist


    【解决方案1】:

    我不确定 react-persist 是如何工作的。但我认为您想像这样将 exact 道具添加到 Home 的路线中:

    <Route path="/" exact component={Home}/>
    

    否则两条路由都会渲染,并且当每个组件渲染时,可能会触发您看到的双重操作。

    【讨论】:

    • 我试图添加确切的道具,但它并没有解决问题。我附上了一张 react redux 状态的图片
    【解决方案2】:

    我查看了文档,似乎persistStore() 可能会触发补液操作,因此可能不需要autoRehydrate()

    提供自动补水是为了方便。在大型应用程序中, 或具有非典型还原剂成分的一种,可能不会自动补液 方便的。在这种情况下,只需省略 autoRehydrate。补液 操作仍将由 persistStore 触发,然后可以处理 单独通过减速器或使用自定义补液处理程序。

    所以尝试删除autoRehydrate()

    【讨论】:

    • 感谢您的帮助!我试图删除 autoRehydrate(),行为仍然相同(只是破坏了一些组件)。我想商店会保存每条路线的状态。
    【解决方案3】:

    补水是创建商店后的第二步,其他任何事情都应该在补水回调中完成。

    它是persiststore func 中的第三个参数。 persistStore(store, [config, callback])

    看看使用补液回调是否有帮助。

    【讨论】:

      猜你喜欢
      • 2018-12-28
      • 2021-02-28
      • 2018-01-14
      • 2020-02-26
      • 2016-08-24
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多