【问题标题】:Get response data from Axios using redux thunk使用 redux thunk 从 Axios 获取响应数据
【发布时间】:2018-07-03 19:18:08
【问题描述】:

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

视频播放器.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-thunk 处理了这个。

标签: reactjs asynchronous redux axios redux-thunk


【解决方案1】:

您正在使用 Redux。您的操作创建者不会直接返回 URL,它会调度操作并更新您的状态。在 componentDidMount 中使用你的动作创建者。因此,这会更新您的状态。然后使用 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 更改为减速器的州名称。

【讨论】:

  • 谢谢!我现在测试了它,它可以工作!现在这对我来说更有意义了。
猜你喜欢
  • 2017-10-04
  • 2018-04-12
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 2018-12-02
  • 2020-03-22
  • 2017-10-31
  • 2021-07-27
相关资源
最近更新 更多