首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用redux thunk从Axios获取响应数据

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

Stack Overflow用户
提问于 2018-07-04 03:18:09
回答 1查看 1.2K关注 0票数 0

我正在尝试使用Axios和redux从API响应调用返回一些数据。然而,我被困在如何检索数据的问题上。日志工作得很好,但我似乎无法访问promise中的数据。任何帮助都将不胜感激。

Videoplayer.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);

index.js (actions文件夹)

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 });
};

genreReducer.js

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

export default function(state = null, action) {
    switch (action.type) {
        case FETCH_SONG:
            console.log(action.payload);
            return action.payload;

        default: 
            return state;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-04 03:35:21

您正在使用Redux。您的操作创建者不会直接返回URL,它会调度一个操作并更新您的状态。在componentDidMount中使用您的操作创建器。所以,这会更新你的状态。然后用mapStateToProps使用这个状态来访问你的数据,网址在这里。如下所示:

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

class Videoplayer extends Component {
    componentDidMount() {
        this.props.fetchSong("house");
    }

    render() {
        return (
            <video className="responsive-video" controls autoPlay>
                <source src={this.props.songURL} type="video/mp4"></source>
            </video>
        )
    }
}

const mapStateToProps = state => ({
    songURL: state.yourStateName,
});

export default connect(mapStateToProps, actions)(Videoplayer);

yourStateName更改为您的reducer的状态名称。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51161590

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档