让PersistGate的onBeforeLift调用另一个动作创建者

时间:2018-02-06 21:41:07

标签: react-native redux redux-persist

我在React Native应用程序的Redux-Persist上使用PersistGate进行基本设置,以检查凭据是否仍然良好。如果它们不好,那么它会清除并重置商店。如果凭据 好,我想要做的就是调用一个动作。但是当我调度动作时,我得到“fetchData未定义”错误。

import React from 'react'
import { AppRegistry, View } from 'react-native'
import { Provider } from 'react-redux'
import Application from './src/containers/gen/Application'
import rootReducer from './src/reducers'
import { createStore, applyMiddleware } from 'redux'
import { persistStore, persistCombineReducers } from 'redux-persist'
import { PersistGate } from 'redux-persist/es/integration/react'
import reduxReset from 'redux-reset'
import storage from 'redux-persist/es/storage'
import {fetchData} from './src/actions/auth'
import { default as thunk } from 'redux-thunk'

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

const reducer = persistCombineReducers(config, rootReducer)

function configureStore () {
  let store = createStore(reducer,
    applyMiddleware(thunk),
    reduxReset()
  )
  let persistor = persistStore(store)
  return { persistor, store }
}

const { persistor, store } = configureStore()

export default class App extends React.Component {
  _serverSync(store) {
    const state = store.getState()

    const uid = state.reducers.auth.credentials.uid
    const client = state.reducers.auth.credentials.client
    const access_token = state.reducers.auth.credentials['access-token']

    if (!uid && !client && !access_token) return

    fetch('https://url/api/v1/auth/validate_token?uid=' + uid + '&client=' + client + '&access-token=' + access_token)
      .then( (response) => {
        if(!response.ok) {
          persistor.purge()
          store.dispatch({ type: 'RESET' })
        } else {
          store.dispatch(fetchData(state.reducers.auth.credentials))
        }
      })
  }

  render () {
    return (
      <Provider store={store}>
        <PersistGate
          persistor={persistor}
          onBeforeLift={() => this._serverSync(store)}
          >
          <View style={{flex: 1}}>
            <Application />
          </View>
        </PersistGate>
      </Provider>
    )
  }
}

我觉得这可能是一个新手问题,因为访问函数似乎是我应该做的事情。值得注意的是fetchData动作创建器在应用程序内部使用时工作正常。

这是我从(src / actions / auth'里面)导出fetchData的地方:

export const fetchData = (credentials, _id, admin) => {
  return (dispatch) => {
    fetch('https://url.com/mobile/users/'+ _id.toString() +'/initialize', {
      method: 'GET',
      headers: credentials
    }).then((response) => {
      if (response.status === 200) {
        return (dispatch(storeData(response, admin)))
      } else {
        response.json().then((body) => {
          console.log(body)
          return (dispatch(loginErrors(body.error + ' ' + body.exception)))
        })
      }
    })
  }
}

0 个答案:

没有答案