Redux保留,数据不保留

时间:2019-07-11 09:10:32

标签: reactjs react-native react-redux redux-persist

我正在使用redux-persist,我的数据正在保留,但是在启动我的应用程序时被VIDEOS_SUCCESS覆盖。如何防止这种情况并保留我的数据?

减速器:

case "VIDEOS_SUCCESS": {
    const { data } = action;
    let videos = [];
    let questions = [];
    data.map(item => {
        const {
            id,
            title: { rendered: title },
            content: { rendered: description },
            youtubeVideo,
            ...
            icon
        } = item;

        const newVideo = {
            id,
            title,
            preview: trimText(description, 100),
            description,
            youtubeVideo,
            bookMarked: false,
            ...
            current: 0,
            correctScore: 5,
            totalScore: 50,
            results: {
                score: 0,
                correctAnswers: 0
            },
            completed: false,
            icon
        };

        videos.push(newVideo);
    });

    return videos;
}

商店:

import { createStore, applyMiddleware } from "redux";
import { persistStore, persistReducer, autoRehydrate } from "redux-persist";
import storage from "redux-persist/lib/storage";
import thunk from "redux-thunk";

import logger from "redux-logger";
import rootReducer from "../reducers";

const persistConfig = {
    key: "root",
    storage: storage, 
    whitelist: ["videos"],
    timeout: null
};

const pReducer = persistReducer(persistConfig, rootReducer);

export const store = createStore(pReducer, applyMiddleware(thunk, logger));
export const persistor = persistStore(store);

export default store;

应用程序:

import { store, persistor } from "./config/configureStore";
import { PersistGate } from "redux-persist/integration/react";
import AppNavigator from "./navigation/AppNavigator";
import NavigationService from "./navigation/actions";

export default class App extends React.Component {
  render() {
    return (
      <ImageBackground
        source={require("./assets/images/TC_background.jpg")}
        style={styles.container}
      >
        <Provider store={store}>
          <PersistGate loading={null} persistor={persistor}>
            <AppNavigator
              ref={navigatorRef => {
                NavigationService.setTopLevelNavigator(navigatorRef);
              }}
            />
          </PersistGate>
        </Provider>
      </ImageBackground>
    );
  }
}

我从默认路由获取数据:

import DrawerHeader from "../navigation/DrawerHeader";
class HomeScreen extends React.Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    const { fetchData } = this.props;
    fetchData();
  }

  render() {
    const { videos } = this.props;
    return (
      <View style={styles.container}>
        <HomeMenu {...this.props} />
      </View>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  fetchData: () => dispatch(fetchData())
});
const mapStateToProps = state => {
  return {
    videos: state.videos
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(HomeScreen);

我的补水工作正常,但是VIDEO_SUCCESS nextState显示了初始提取数据。

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以删除此行。

// check if state exists from persist, and return, otherwise fetch from
if (Array.isArray(state) && state.length > 0) {
    return state;
}

答案 1 :(得分:0)

如果您使用的是最新版本的redux-persist,则无需执行此操作。 只要您保持状态(根减少器),就会自动调用Rehydrate()。

case "persist/REHYDRATE": {
    if (action && action.payload) {
        const {
            payload: { videos }
        } = action;
        return videos;
    }

    return [];

但是请确保您的应用程序被persistGate包装。

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

通过转换,您可以自定义持久化并重新水化的状态对象。 如果您需要帮助,请查看redux-persist文档。