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

Get response data from Axios using redux thunk

我正在尝试 return 来自 API 响应调用的一些数据,使用 Axios 和 redux。但是,我坚持我应该如何检索数据。日志记录工作正常,但我似乎无法访问承诺中的数据。任何帮助将不胜感激。

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(操作文件夹)

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

您正在使用 Redux。您的动作创建者不会直接 ​​return 一个 URL,它会调度一个动作并更新您的状态。在 componentDidMount 中使用你的 action creator。所以,这会更新你的状态。然后使用 mapStateToProps 使用这个状态来到达你的数据,URL 这里。像这样:

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 更改为您所在州的减速器名称。