Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/451.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用中间件在Redux应用程序中编写localStorage?_Javascript_Reactjs_Redux_Middleware - Fatal编程技术网

Javascript 如何使用中间件在Redux应用程序中编写localStorage?

Javascript 如何使用中间件在Redux应用程序中编写localStorage?,javascript,reactjs,redux,middleware,Javascript,Reactjs,Redux,Middleware,我正在创建一个应用程序,它使用OpenWeatherAPI获取用户输入的城市列表及其各自的天气。因此,我希望城市在刷新页面后保持不变。我知道如何使用浏览器localStorage API保存数据。但我不知道如何通过中间件将其持久化并将其传递给提供商 下面是我的主Index.js文件-: import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; impor

我正在创建一个应用程序,它使用OpenWeatherAPI获取用户输入的城市列表及其各自的天气。因此,我希望城市在刷新页面后保持不变。我知道如何使用浏览器localStorage API保存数据。但我不知道如何通过中间件将其持久化并将其传递给提供商

下面是我的主Index.js文件-:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';

import App from './components/app';
import reducers from './reducers';
import {loadState,saveState} from './localStorage';

const persistedState=loadState();
const store=createStore(persistedState);

store.subscribe(()=>{
store.getState()
});

const createStoreWithMiddleware =
     applyMiddleware(ReduxPromise)(createStore);

ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container-fluid'));
export const loadState=()=>{
try{
    const serializedState=localStorage.getItem('state');
    if(serializedState===null){
        return undefined;
    }
    return JSON.parse(serializedState);
}catch(err){
    return undefined;
}
};

export const saveState=(state)=>{
try {
    const serializedState=JSON.stringify(state);
    localStorage.setItem('state',serializedState);
}catch(err){
    console.log(err);
}};
我已经在reducers文件夹中的不同文件中编写了reducer

减速器/index.js-:

import { combineReducers } from 'redux';
import WeatherReducer from './reducer_weather';

const rootReducer = combineReducers({
weather:WeatherReducer
});

export default rootReducer;
和另一个减速器 减速器/减速器\u weather.js-:

import {FETCH_WEATHER} from '../actions/index';
import {DELETECITY} from '../actions/deleterow';
export default function(state=[],action){

switch(action.type){
    case FETCH_WEATHER:
        console.log([action.payload.data, ...state]);
        return [action.payload.data, ...state];
    case DELETECITY:
        console.log([...state].filter((weather)=>{
            return weather.city.id!==action.payload
        }));
        return [...state].filter((weather)=>{
            return weather.city.id!==action.payload
        });
    default:
        return state;

    }; 
}
在使用localStorage来持久化应用程序状态之前,我的代码运行良好。但现在它向我展示了一个错误。我面临一个关于
constcreatestorewithmiddleware的问题=
applyMiddleware(ReduxPromise)(createStore)


如何使用此中间件使用store,以及如何传入标签的store属性

我建议您使用

保存并重新水化redux存储

使用此中间件,Redux存储中的所有数据都将自动保存到本地存储中(也可以使用不同类型的存储)。因此,刷新页面时,来自上一个请求的已保存数据将自动重新水化(推送)回存储区


示例,摘自文件: 配置

// configureStore.js

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

import rootReducer from './reducers'

const persistConfig = {
  key: 'root',
  storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export default () => {
  let store = createStore(persistedReducer)
  let persistor = persistStore(store)
  return { store, persistor }
}
import { PersistGate } from 'redux-persist/integration/react'

// ... normal setup, create store and persistor, import components etc.

const App = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <RootComponent />
      </PersistGate>
    </Provider>
  );
};
用法

// configureStore.js

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

import rootReducer from './reducers'

const persistConfig = {
  key: 'root',
  storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export default () => {
  let store = createStore(persistedReducer)
  let persistor = persistStore(store)
  return { store, persistor }
}
import { PersistGate } from 'redux-persist/integration/react'

// ... normal setup, create store and persistor, import components etc.

const App = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <RootComponent />
      </PersistGate>
    </Provider>
  );
};
从'redux persist/integration/react'导入{PersistGate}
// ... 正常设置、创建存储和持久化、导入组件等。
常量应用=()=>{
返回(
);
};

谢谢你的回答。但是在我的主index.js文件中,我在哪里使用
createStoreWithMiddleware(reducers)
?我想在Provider标记的store属性中提供结果@首先,您没有将正确的参数传递给函数。您应该将减速器作为第一个参数传递,而不是传递预加载状态。预加载状态(
persistedState
)应作为第二个参数传递。我还建议您检查文档以及如何使用它。但是,我建议您使用
redux persist
。它易于配置,并且与您想要的功能完全相同。只需将其配置到您的项目中,您就可以动态地使用localStorage持久性。你为什么不试试呢?