使用redux thunk从Axios获取响应数据

时间:2018-07-03 19:18:09

标签: reactjs asynchronous redux axios redux-thunk

我正在尝试使用Axios和redux从API响应调用返回一些数据。但是,我被困在应该如何检索数据的地方。日志记录工作正常,但是我似乎无法从Promise访问数据。任何帮助将不胜感激。

Videoplayer.js

| Serial_No | From_Container | Part_Key | Part_Operation_Key |
|-----------|----------------|----------|--------------------|
|      1234 |           1233 |     5678 |                  5 |
|      1233 |           1232 |     5678 |                  4 |

index.js(动作文件夹)

    import React, { Component } from 'react';
    import { connect } from "react-redux";
    import * as actions from "../actions";

    class Videoplayer extends Component {
        renderContent() {
            return this.props.fetchSong("house"); // this SHOULD return a URL
        }

        render() {
            return (
                <video className="responsive-video" controls autoPlay>
                    <source src={this.renderContent()} type="video/mp4"></source>
                </video>
            )
        }
    }
    export default connect(null, actions)(Videoplayer);

genreReducer.js

import axios from "axios";
import { FETCH_SONG } from "./types";

export const fetchSong = category => async dispatch => {
    const res = await axios.get(`/api/${category}`);
    dispatch({ type: FETCH_SONG, payload: res.data });
};

1 个答案:

答案 0 :(得分:2)

您正在使用Redux。您的动作创建者不会直接返回URL,而是会分派一个动作并更新您的状态。在componentDidMount中使用动作创建者。因此,这将更新您的状态。然后使用mapStateToProps使用此状态访问您的数据,网址为URL。像这样:

                string data = File.ReadAllText("D://readXML.txt");
                //From File i am reading XML
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(data);
                XmlNodeList list = xdoc.SelectNodes("//Doc");
                List<string> nodeNames = new List<string>();

                foreach (System.Xml.XmlNode node in xdoc.SelectNodes("//Doc/Items"))
                {
                    foreach (System.Xml.XmlNode child in node.ChildNodes)
                    {
                        if (!nodeNames.Contains(child.Name)) nodeNames.Add(child.Name);
                    }
                }

XmlDocument doc = new XmlDocument(); doc.LoadXml("<reply success=\"true\">More nodes go here</reply>"); XmlElement root = doc.DocumentElement; string s = root.Attributes["success"].Value; 更改为减速器的状态名称。