如何在`onClick`事件中调用Redux Saga操作?
我刚刚使用infinitered/ignite启动了一个新项目。
我已将getUserToken
函数添加到APITestScreen
因此,我知道该函数按预期工作,但我无法将onPress
函数与I added to the LaunchScreen按钮挂钩。
我已将其导入到视图中,但当我单击该按钮时没有任何反应。我已经添加了一个警报和一个sole.log,但它们没有被触发。我应该怎么做才能使fetchUserToken在我单击该按钮时运行?
整个项目已发布posted at Github。
我的看法
import getUserToken from '../Sagas/AuthSagas.js';
<RoundedButton text="Fetch token" onPress={ getUserToken } />
App/Redux/AuthRedux.js
import { createReducer, createActions } from 'reduxsauce'
import Immutable from 'seamless-immutable'
/* ------------- Types and Action Creators ------------- */
const { Types, Creators } = createActions({
tokenRequest: ['username'],
tokenSuccess: ['token'],
tokenFailure: null
})
export const AuthTypes = Types
export default Creators
/* ------------- Initial State ------------- */
export const INITIAL_STATE = Immutable({
token: null,
fetching: null,
error: null,
username: null
})
/* ------------- Reducers ------------- */
// request the token for a user
export const request = (state, { username }) =>
state.merge({ fetching: true, username, token: null })
// successful token lookup
export const success = (state, action) => {
const { token } = action
return state.merge({ fetching: false, error: null, token })
}
// failed to get the token
export const failure = (state) =>
state.merge({ fetching: false, error: true, token: null })
/* ------------- Hookup Reducers To Types ------------- */
export const reducer = createReducer(INITIAL_STATE, {
[Types.TOKEN_REQUEST]: request,
[Types.TOKEN_SUCCESS]: success,
[Types.TOKEN_FAILURE]: failure
})
App/Sagas/AuthSagas.js
import { call, put } from 'redux-saga/effects'
import { path } from 'ramda'
import AuthActions from '../Redux/AuthRedux'
export function * getUserToken (api, action) {
console.tron.log('Hello, from getUserToken');
alert('in getUserToken');
const { username } = action
// make the call to the api
const response = yield call(api.getUser, username)
if (response.ok) {
const firstUser = path(['data', 'items'], response)[0]
const avatar = firstUser.avatar_url
// do data conversion here if needed
yield put(AuthActions.userSuccess(avatar))
} else {
yield put(AuthActions.userFailure())
}
}
sagas/index.js
export default function * root () {
yield all([
// some sagas only receive an action
takeLatest(StartupTypes.STARTUP, startup),
// some sagas receive extra parameters in addition to an action
takeLatest(GithubTypes.USER_REQUEST, getUserAvatar, api),
// Auth sagas
takeLatest(AuthTypes.TOKEN_REQUEST, getUserToken, api)
])
}
解决方案
SAGA很棒,因为它们允许长时间运行的流程以完全分离的方式控制应用程序流,并且可以通过操作进行排序,允许您并行化/取消/分叉/协调SAGA以在中央位置协调您的应用程序逻辑(即,将其视为能够将操作链接在一起,在此过程中合并副作用)
导入生成器函数并像普通函数一样直接调用它将不起作用,如果这样做将绕过SAGA功能,例如,如果您第二次或第三次按下该按钮,它将始终从头到尾再次执行整个生成器,这可能会导致您尝试存储或使用令牌,然后该令牌会立即被后续SAGA无效
更好的做法是让您的传奇始终监听特定的操作,以触发进一步的工人传奇,保持他们的脱钩,并允许他们控制自己的流程。
在这种情况下,您将调度一个操作onPress
,并让一个长时间运行的父传奇侦听该操作,然后将其移交给当前的操作来完成实际工作。此侦听事件将使用takeLatest
来控制取消先前的调用,从而取消先前的事件调用,以便在前一个事件仍在运行时的后续按钮按下将始终优先,并且您的令牌不会意外失效
//AuthActions.js
// add a new action (or more probably adapt fetchUserToken to suit)...
export const GET_USER_TOKEN = 'auth/get-user-token'
export const getUserToken = (username) => ({
type: GET_USER_TOKEN,
payload: username
})
//查看
import {getUserToken} from './AuthActions'
// this now dispatches action (assumes username is captured elsewhere)
// also assumes store.dispatch but that would more likely be done via `connect` elsewhere
<RoundedButton text="Fetch token" onPress={ () => store.dispatch(getUserToken(this.username)) } />
//AuthSagag.js
import api from 'someapi'
import actions from 'someactions'
import {path} from 'ramda'
import {put, call, takeLatest} from 'redux-saga/effects'
import AuthActions from '../Redux/AuthRedux'
// this will be our long running saga
export function* watchRequestUserToken() {
// listens for the latest `GET_USER_TOKEN` action,
// `takeLatest` cancels any currently executing `getUserToken` so that is always up to date
yield takeLatest(AuthActions.GET_USER_TOKEN, getUserToken)
}
// child generator is orchestrated by the parent saga
// no need to export (unless for tests) as it should not be called by anything outside of the sagas
function* getUserToken (action) { // the actual action is passed in as arg
const username = action.payload
// make the call to the api
const response = yield call(api.getUser, username)
if (response.ok) {
const firstUser = path(['data', 'items'], response)[0]
const avatar = firstUser.avatar_url
// do data conversion here if needed
yield put(AuthActions.userSuccess(avatar))
} else {
yield put(AuthActions.userFailure())
}
}
//main.js(来自https://redux-saga.js.org/)改编为套件
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import {reducer} from './AuthRedux'
import {watchRequestUserToken} from './AuthSagas'
// create the saga middleware
const sagaMiddleware = createSagaMiddleware()
// mount it on the Store
export const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
)
// then run the saga
sagaMiddleware.run(watchRequestUserToken)
相关文章