如何使用ReactNative和Redux获取API数据

时间:2018-09-19 03:02:56

标签: react-native redux react-native-ios

我正在创建此组件以从“ https://facebook.github.io/react-native/movies.json”文件中获取数据。我正在尝试将其作为测试应用程序,后来计划使用我的实际API端点。但是,我正在努力在屏幕上显示数据。它不会出现任何错误或显示错误。如何添加活动指示器以检查数据是否正在获取并在其中显示数据?

动作

import {
  FETCHING_ASSISTANT_REQUEST,
  FETCHING_ASSISTANT_SUCCESS,
  FETCHING_ASSISTANT_FAILURE
} from "./types";

export function fetchAssistantRequest() {
  return {
    type: FETCHING_ASSISTANT_REQUEST
  };
}

export function fetchAssistantFailure(errorMessage) {
  return {
    type: FETCHING_ASSISTANT_FAILURE,
    errorMessage
  };
}

export const fetchAssistant = () => {
  return async dispatch => {
    dispatch(fetchAssistantRequest());
    try {
      let response = await fetch(
        "https://facebook.github.io/react-native/movies.json"
      );
      let json = await response.json();
      dispatch(fetchAssistantSuccess(json.results));
    } catch (error) {
      dispatch(fetchAssistantFailure(error));
    }
  };
};

减速器

import {
  FETCHING_ASSISTANT_REQUEST,
  FETCHING_ASSISTANT_SUCCESS,
  FETCHING_ASSISTANT_FAILURE
} from "../actions/types";

//initial states
const initialState = {
  isFetching: false,
  errorMessage: null,
  assistant: []
};

export default function assistantReducer(state = initialState, action) {
  switch (action.type) {
    //fetching state
    case FETCHING_ASSISTANT_REQUEST:
      return { ...state, isFetching: true };
    //success state
    case FETCHING_ASSISTANT_SUCCESS:
      return { ...state, isFetching: false, assistant: action.data };
    //faliuer state
    case FETCHING_ASSISTANT_FAILURE:
      return { ...state, isFetching: false, errorMessage: action.errorMessage };

    default:
      return state;
  }
}

App Reducer

import .. from ".."
const AppReducer = combineReducers({
  auth: AuthReducer,
  // assis: AssistanceReduer,
  // assistant: DumyReducer,
  assis: AssisReducer
});

export default AppReducer;

应用

import React, { Component } from "react";
import { View, Text, StyleSheet } from "react-native";
import { connect } from "react-redux";

import { fetchAssistant } from "../actions/AssistantAction";

class Assistant extends React.Component {
  componentDidMount() {
    this.props.getAssistance;
  }
  render() {
    return (
      <View>
        <Text> {this.props.assistant.assistant.title}</Text>
        <Text>{JSON.stringify(this.props.assistant.assistant.title)}</Text>
      </View>
    );
  }
}
function mapStateToProps(state) {
  return {
    assistant: state.assis
  };
}

function mapDispatchToProps(dispatch) {
  return {
    getAssistance: () => dispatch(fetchAssistant())
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Assistant);

存储

import { createStore, applyMiddleware, compose } from "redux";
import { composeWithDevTools } from "remote-redux-devtools";
import thunk from "redux-thunk";
import AppReducer from "../reducers/AppReducer";

const store = createStore(
  AppReducer,
  {}, // initial state
  composeWithDevTools(applyMiddleware(thunk))
);

export default store;

2 个答案:

答案 0 :(得分:2)

这是未经测试的解决方案,但它可以工作。 要显示活动指示器,您必须在redux存储中使用isFetching变量。由于“助手”是一个数组,因此您必须使用map()来显示每个项目。当然,更好的解决方案是FlatList。

import React, { Component } from "react";
import { View, Text, StyleSheet, ActivityIndicator } from "react-native";
import { connect } from "react-redux";

import { fetchAssistant } from "../actions/AssistantAction";

class Assistant extends React.Component {
  componentDidMount() {
    this.props.getAssistance();
  }

  render() {
    if(this.props.isFetching) return (<ActivityIndicator size="small" color="#00ff00" />);

    return (
      <View>
        {this.props.assistant.assistant.map(item => <Text key={item.id}>{item.title}</Text>)}
      </View>
    );
  }
}
function mapStateToProps(state) {
  return {
    isFetching: state.isFetching,
    assistant: state.assis
  };
}

function mapDispatchToProps(dispatch) {
  return {
    getAssistance: () => dispatch(fetchAssistant())
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Assistant);

答案 1 :(得分:0)

好吧,看来fetchAssistantSuccess文件中没有定义您的Actions函数,所以我不确定 action 的调度方式。您将需要

Action.js

export function fetchAssistantSuccess(payload) {
  return {
    type: FETCHING_ASSISTANT_SUCCESS,
    payload
  };
}

和您的 Reducer.js

case FETCHING_ASSISTANT_SUCCESS:
      return { ...state, isFetching: false, assistant: action.payload};

此外,您可能希望使用postman之类的东西分别测试端点 以确保它传递正确的数据。