如何在 react-native 和 Redux 的 action creator 中获取全局状态?

How to get the global state in an action creator in react-native and Redux?

我已经使用带有 rails 后端的 JWT 成功登录了我的用户。并使用 Redux 和 Redux-thunk.

user object 存储在我的 react-native 应用程序的全局商店中

但是,我现在需要在我的其他操作中访问 state.user.authentication_token,我需要执行后端 fetch 请求以使用适当的 header 获得我的数据并获得授权令牌。

这是我的 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);
    });
  };
};

我需要从状态访问用户 object 并将 fetch 请求中的 header 替换为 X-User-TokenX-User-Email其中一个存储在用户 object 的状态中。但是,我无法在操作文件中访问我的状态。

我在这里错过了什么?如何全局访问其他文件中的状态?

我有一段时间没有使用 redux,但这听起来是 thunk.

的完美情况

编辑 1 - 重读你的问题,看来你已经是了。所以只需传入第二个参数,这将是函数 getState.

export const fetchAssets = () => {
  return (dispatch, getState) => {
    const { user } = getState();
    // user.token == token

    // .. rest
  };
}

https://github.com/gaearon/redux-thunk http://redux.js.org/docs/advanced/AsyncActions.html

编辑 2

不是针对你的问题,我会在这里做一个巨大的假设,但你的令牌实际上是状态的一部分 - 我的意思是应该是吗?除非应用程序更改它,否则它 不需要 成为您商店的一部分。不要陷入认为一切都必须在 redux 存储中的常见陷阱。