首页 > 解决方案 > 如何将 redux-saga 与 redux-persist 或替代品一起使用?

问题描述

我想在应用程序启动时从 API 获取一些数据。在我的应用程序中,我坚持使用 redux,现在我决定使用 redux saga,但它不起作用。不过,我有一个项目的代码实际上至少要花费 20 万美元,所以我重复了该代码。它仍然无法正常工作。我认为,该函数调度不执行。这是我的代码。如果您不知道解决方案,请告诉我替代方案,因为截止日期:)

应用程序.tsx

const App: React.FC = () => {
  const {store, persistor} = configureStore();
  return (
    <Provider store={store}>
      <PersistGate persistor={persistor} loading={null}>
        <Navigator />
      </PersistGate>
    </Provider>
  );
};

配置存储

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const sagaMiddleware = createSagaMiddleware();

export default () => {
  const store = createStore(
    persistedReducer,
    compose(
      applyMiddleware(sagaMiddleware),
    ),
  );
  sagaMiddleware.run(rootSaga);
  const persistor = persistStore(store);
  return {store, persistor};
};

mapToDispatchProps

const mapDispatchToProps = (dispatch: any) => {
  return {
    changeWiFiState: (state: boolean) => {
      dispatch(changeWiFiState(state));
    },
    addToScannedCodesNoWifi: (item: string) => {
      dispatch(addToScannedCodesNoWifi(item));
    },
    changeCart: (item: any) => {
      dispatch(changeCart(item));
    },
    saveLocal: (item: any) => {
      console.log('fsf')
      dispatch({type: "SET_LOCAL_STORAGE_REQUESTED"})
    }
  };
};
const ScannerScreen = connect(
  mapStateToProps,
  mapDispatchToProps,
)(_ScannerScreen);
export {ScannerScreen}

根佐贺

export default function* rootSaga() {

    takeEvery("SET_LOCAL_STORAGE_REQUESTED", saveLocal)
}

保存本地

function* saga() {
    axios.get('https://server-for-rn.herokuapp.com/code/codes').then(response => {
        console.log(response.data)
        return doArr(response.data)
    })
}

export function* saveLocal() {
    console.log('fdsfgs')
    let res = call(saga)
    yield put ({type: "SET_LOCAL_STORAGE", payload: res})
}

标签: react-nativereduxreact-reduxredux-sagaredux-persist

解决方案


推荐阅读