如何在React Redux中根据API调用的结果创建数组

时间:2020-10-11 05:07:41

标签: api redux

我使用API​​获得了流行电影的所有IMDB电影ID。然后,我调用另一个API来获取每个电影ID的电影详细信息,并将它们推入数组。但是,当我检查数组内容时,它仅包含我最近推送的数据。如何将所有结果值存储在数组中,以便以后在页面上显示它们。

index.js(操作)

LineChartData(
  ...
  lineTouchData: LineTouchData(
      touchTooltipData: LineTouchTooltipData(
        getTooltipItems: (value) {
          return value
              .map((e) => LineTooltipItem(
                  "${e.y < 0 ? 'Expense:' : 'Income:'} ${e.y.toStringAsFixed(2)} \n Diff: ",
                  TextSetting.text14))
              .toList();
        },
        tooltipBgColor: AppColour.mainBlue,
      )
  ...

)

从第一个API获得结果并将其作为道具传递给它后,查看文件以调用第二个API

import axios from "axios";
const url = "http://www.omdbapi.com/?i=";
    
// The First API Call which gives me all the ids
export function getIMDBtitle() {
  const output = axios({
     method: "GET",
     url: "https://imdb8.p.rapidapi.com/title/get-most-popular-movies",
     headers: {
       "content-type": "application/octet-stream",
       "x-rapidapi-host": "imdb8.p.rapidapi.com",
       "x-rapidapi-key": "************************",
       useQueryString: true,
     },
     params: {
        purchaseCountry: "US",
        homeCountry: "US",
        currentCountry: "US",
     },
  })
    
  //The 2nd API call that gives me the details but takes one id at a time
  export function getMovies(id){
    const output = axios.get(`${url}${id}&&apikey=******`)
      return {
        type: "GET_MOVIES",
        payload: output,
      };
  }

减速机

import React, { Component } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { getMovies } from "../Actions";
    
class GetMovies extends Component {
  render() {
    const rederDetailes = ({ titles }) => {
      if (titles) {
        var i;
        for (i = 0; i < titles.data.length; i++) {
          var id = titles.data[i].substring(7, titles.data[i].length - 1);
          this.props.dispatch(getMovies(id));
        }
      }
    };
    
    return (
      <React.Fragment>
        <h1>Movies</h1>
          {rederDetailes(this.props)}
        </React.Fragment>
    );
  }
}
    
GetMovies.protoType = {
   dispatch: PropTypes.func,
};

function mapStateToProps(state) {
   var a = [];
   a.push(state);
   console.log(a);
}

export default connect(mapStateToProps)(GetMovies);

商店

export default function (state = {}, action) {
  switch (action.type) {
    case "GET_IMDB_TITLES":
      return { ...state, moviesTitle: action.payload };
    case "GET_MOVIES":
      return { ...state, moviesDetail: action.payload };
    default:
      return state;
    }
}  

结果在控制台上

import { createStore, applyMiddleware } from "redux";
import promiseMiddleware from "redux-promise";
import logger from "redux-logger";
import Reducer from "../Reducers";
    
let Store = createStore(Reducer, applyMiddleware(promiseMiddleware, logger));
    
export default Store;

0 个答案:

没有答案