使用Redux Thunk中间件,我正在实现API调用。
但是在React Router中使用onEnter
时,我遇到了问题。
这是我的一些代码:
-router.js
import React from 'react';
import { Route, IndexRoute, Router } from 'react-router';
import Layout from './components/Layout';
import Landing from './components/Landing';
import Test from './components/test';
import { getCurrentUser } from './actions/user.actions';
import { fetchUser } from './actions/user.actions';
import requireAuth from './lib/requireAuth';
// import waitingForAuth from './lib/waitingForAuth';
import store from './store';
export default (
<Router>
<Route path="/" component={Layout} onEnter=
{store.dispatch(getCurrentUser())}>
<IndexRoute component={requireAuth(Landing)} />
</Route>
<Route path="/test" component={Layout} onEnter=
{store.dispatch(fetchUser())}>
<IndexRoute component={Test} />
</Route>
</Router>
);
-user.action.js
export function getCurrentUser() {
return function (dispatch) {
dispatch({ type: 'USER_CURRENT_PENDING' });
dispatch({
type: 'USER_CURRENT_FULFILLED', payload: [{
Name: 'username',
Value: 'test@user.com'
}, {
Name: 'name',
Value: 'Test'
}, {
Name: 'family_name',
Value: 'User'
}, {
Name: 'email',
Value: 'test@user.com'
}, {
Name: 'phone_number',
Value: '555-11111'
}]
});
}
}
export const REQUEST = 'API_REQUEST';
function requestUser() {
return {
type: REQUEST
}
}
export const RECEIVE = 'API_RECEIVE';
function receiveUser(user) {
return {
type: RECEIVE,
payload: {
user
}
}
}
export const FAILURE = 'API_FAILURE';
function failureUser(message) {
return {
type: FAILURE,
payload: {
message
}
}
}
export function fetchUser() {
console.log('fetchUser');
return function (dispatch) {
dispatch(requestUser())
return fetch(`https://jsonplaceholder.typicode.com/posts/1`)
.then(response => {
if (response.status >= 400) {
dispatch(failureUser("Bad response from server"));
}
return response.json();
})
.then(user =>
dispatch(receiveUser(user))
);
}
}
-userReducer.js
...
case 'API_RECEIVE':
const userInfo = {
userId: 0,
id: 0,
title: '',
body: ''
}
action.payload.forEach(function (attribute) {
switch (attribute.Name) {
case 'userId':
userInfo.userId = attribute.Value;
break;
case 'id':
userInfo.id = attribute.Value;
break;
case 'title':
userInfo.title = attribute.Value;
break;
case 'body':
userInfo.body = attribute.Value;
break;
default:
break;
}
}, this);
return {
...state,
loggedIn: true,
loggingIn: false,
userId: userInfo.userId,
id: userInfo.id,
title: userInfo.title,
body: userInfo.body,
loginRedirect: undefined,
loginError: undefined
}
default:
return state;
}
帮助我!!!
答案 0 :(得分:0)
我找到了解决方案。
要解决此问题,我不必return
action
,如下所示:
export function fetchUser() {
console.log('fetchUser');
function (dispatch) {
dispatch(requestUser())
fetch(`https://jsonplaceholder.typicode.com/posts/1`)
.then(response => {
if (response.status >= 400) {
dispatch(failureUser("Bad response from server"));
}
return response.json();
})
.then(user =>
dispatch(receiveUser(user))
);
}
}