我正在尝试使用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;
}
}
发布于 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的状态名称。
https://stackoverflow.com/questions/51161590
复制相似问题