我正在使用 MERN 堆栈结构和 Redux,我遇到了 isomorphic-fetch 模块的问题。
我想从会话中获取用户信息,但是 isomorphic-fetch 模块似乎它的请求与用户会话分开。
以下是视图调度一个动作以从会话中获取用户信息。
MainView.jsx:
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import * as Actions from '../../redux/actions/actions';
class MainView extends React.Component {
constructor(props) {
super(props);
this.displayName = 'MainView';
}
componentWillMount() {
if (this.props.showMessageModal.message !== '') {
this.props.dispatch(Actions.showMessageModal());
}
this.props.dispatch(Actions.fetchUserSession());
}
render() {
const renderTemp = () => {
if (this.props.user) {
return <div>{ JSON.stringify(this.props.user) }</div>;
}
};
return (
<div>
MainView
{ renderTemp() }
</div>
);
}
}
MainView.contextTypes = {
router: React.PropTypes.object,
};
function mapStateToProps(store) {
return {
showMessageModal: store.showMessageModal,
user: store.user,
};
}
MainView.propTypes = {
showMessageModal: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
user: PropTypes.object,
};
export default connect(mapStateToProps)(MainView);
以下是action、reducer和router。
actions.js(仅相关代码):
import * as ActionTypes from '../constants/constants';
import Config from '../../../server/config';
import fetch from 'isomorphic-fetch';
const baseURL = typeof window === 'undefined' ? process.env.BASE_URL || (`http://localhost:${Config.port}`) : '';
export function getUserSession(user) {
return {
type: ActionTypes.GET_USER_SESSION,
user,
};
}
export function fetchUserSession() {
return (dispatch) => {
return fetch(`${baseURL}/api/session-user`)
.then((response) => response.json())
.then((response) => dispatch(getUserSession(response.user)));
};
}
reducer_user.js(结合在 index reducer 中):
import * as ActionTypes from '../constants/constants';
export const user = (state = null, action) => {
switch (action.type) {
case ActionTypes.GET_USER_SESSION :
return action.user;
default:
return state;
}
};
user.router.js(api路由器):
import { Router } from 'express';
router.get('/api/session-user', (req, res) => {
console.log('req.user: ' + req.user);
res.json(req.user);
});
export default router;
登录后,当我直接在浏览器上转到“/api/session-user”时,我可以看到这样的用户信息。
但是当我加载 MainView 并调度操作时,user.router.js 中的“req.user”返回“未定义”。
请猜猜出了什么问题。这将非常有帮助。