我现在正在从redux-saga
练习Official Docs。
我对example有疑问
sagas.js
import {delay} from 'redux-saga';
import {all, call, put, takeEvery} from 'redux-saga/effects';
import axios from 'axios';
const API_ROOT = 'http://localhost:8000';
const postAPIGetToken = ({username, password}) => {
const request = axios({
method: 'post',
url: `${API_ROOT}/api-token-auth/`,
data: {
username,
password
}
});
return request();
};
export function* shootAuth(action) {
const res = yield call(postAPIGetToken, action.payload);
yield put({
type: 'GOT_RESPONSE',
payload: res
})
}
// single entry point to start all Sagas at once
export default function* rootSaga(values) {
const {username, password} = values;
yield all([
helloSaga(),
watchIncrementAsync(),
shootAuth()
])
}
main.js
import "babel-polyfill"
import React from 'react'
import ReactDOM from 'react-dom'
import {createStore ,applyMiddleware} from 'redux'
import createSagaMiddleware from 'redux-saga';
import Counter from './Counter'
import reducer from './reducers'
import {helloSaga} from "./sagas";
import rootSaga from "./sagas";
const sagaMiddleWare = createSagaMiddleware()
const store = createStore(
reducer,
applyMiddleware(sagaMiddleWare)
);
sagaMiddleWare.run(rootSaga);
const action = (type, payload={}) => store.dispatch({type, payload})
function render() {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() => action('INCREMENT')}
onDecrement={() => action('DECREMENT')}
onIncrementAsync={() => action('INCREMENT_ASYNC')}
shootToken={()=>action('SHOOT_TOKEN',
{
username: 'tonyod',
password: 'mbx12345'
})}
/>,
document.getElementById('root')
)
}
render()
store.subscribe(render)
在我的工作项目中。我的react
有redux-form
,能够通过username/password
。这是我的方法。
onSubmit(values) {
const {username, password} = values;
this.props.onSubmitClick(values, REQUEST);
}
我有username
和password
形式。我想把它们传递给saga
。但rootSaga
没有争论。我该如何供应呢?
只需将其他参数传递给sagaMiddleware.run
调用,如下所示:
sagaMiddleWare.run(rootSaga, value);
感谢来自panigrah
gitter的chat-room/reactjs
。
你正在使用sagas登录? Sagas将听取调度方法。因此,在您的操作处理程序中,您将使用有效内容中的用户名和密码参数调度LOGIN之类的操作。在saga中,您可以侦听要调度的LOGIN操作,并从操作有效负载中获取用户名和密码。
因此我采用了错误的实施方式。我模拟单个按钮将发出action
与type
和payload
是用户名和密码。
我错过的是:
1 - 我必须使用store.dispatch(action)
<Counter
value={store.getState()}
shootToken={()=>store.dispatch(
{
type:'SHOOT_ASYNC',
payload: {
username: 'tonyod',
password: '12345'
}
})
}
/>
2 - 我必须在takeEvery
或takeLastest
观看应用程序中的actions
。
const postAPIGetToken = (values) => {
const {username, password} = values;
return axios.post(`${API_ROOT}/api-token-auth/`,
{
username,
password
});
};
export function* shootAuth(action) {
const res = yield call(postAPIGetToken, action.payload);
yield put({
type: 'GOT_RESPONSE',
payload: res
})
}
export function* watchShootAuth() {
yield takeEvery('SHOOT_ASYNC', shootAuth)
}
// single entry point to start all Sagas at once
export default function* rootSaga() {
yield all([
helloSaga(),
watchIncrementAsync(),
watchShootAuth()
])
}
PS。:Ctrl + K
不适用于整个2号代码。它部分适用于它们。