【发布时间】:2017-03-04 08:04:02
【问题描述】:
我已经使用带有 rails 后端的 JWT 成功登录了我的用户。并使用 Redux 和 Redux-thunk 将 user 对象存储在我的 react-native 应用程序的全局存储中。
但是,我现在需要在我的其他操作中访问state.user.authentication_token,我需要在其中执行后端fetch 请求以获取具有适当标头的数据具有授权令牌。
这是我的 AssetList.js 组件:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';
import { fetchAssets } from '../actions';
class AssetsList extends Component {
componentWillMount() {
this.props.fetchAssets();
}
render() {
return (
<View>
<Text>Asset name...</Text>
<Text>Asset name...</Text>
<Text>Asset name...</Text>
<Text>Asset name...</Text>
<Text>Asset name...</Text>
<Text>Asset name...</Text>
</View>
);
}
}
export default connect(null, { fetchAssets })(AssetsList);
这是我的动作文件,它调度动作:
/*global fetch:false*/
import { API_ENDPOINT } from './api';
export const fetchAssets = () => {
return (dispatch) => {
fetch(`${API_ENDPOINT}/assets`, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-User-Token': 'ztUUQuxsnFKhYf8JMLKY', // I need access the user state here
'X-User-Email': 'somecoolemail@gmail.com' // AND HERE...
}
}).then(response => {
dispatch({
type: 'FETCH_SUCCESSFUL'
});
response.json().then(data => {
console.log(data);
}).catch(data => {
console.log(data);
});
}).catch(error => {
console.log(error);
});
};
};
我需要从状态访问用户对象,并将X-User-Token 和X-User-Email 的fetch 请求中的标头替换为用户对象存储在状态中的标头。但是,我无法在操作文件中访问我的状态。
我在这里缺少什么?如何全局访问其他文件中的状态?
【问题讨论】:
标签: javascript reactjs react-native redux react-redux