[英]React-Redux + Redux-Thunk on functional component. Update UI after data is fetched from API
[英]Data not being fetched (React-redux)
嗨,我正在使用 spotify api 做一个项目,我正在尝试获得新版本。 数据正在传递给减速器,但是当我在我的 App 组件中调用 fetch 操作并尝试 console.log 新版本(this.props.newAlbums)时,它是空的。 获取用户数据仍然有效,但获取新版本却不行。
这是我在 actions/index.js 中的 fetch 操作。
export const fetchUserData = (accessToken) => (dispatch) =>{
fetch('https://api.spotify.com/v1/me', {
headers: {'Authorization': 'Bearer ' + accessToken}})
.then(response => response.json())
.then(data =>
dispatch({
type:"FETCH_USER_DATA",
payload: data
})
);
};
export const fetchNewAlbums = (accessToken) => dispatch =>{
fetch('https://api.spotify.com/v1/browse/new-releases?limit=5',{
headers:{'Authorization': 'Bearer ' + accessToken}})
.then(res => res.json())
.then(albums =>
dispatch({
type:"FETCH_NEW_ALBUMS",
payload:albums.albums.items
})
);
}
这是新版本的 reducer (newAlbumReducer.js)
const initialState={
albums:null
}
const newAlbumReducer = (state=initialState,action)=>{
switch(action.type){
case "FETCH_NEW_ALBUMS":
return{
...state,
albums:action.payload
};
default:
return state;
}
}
export default newAlbumReducer;
我的店铺
import {createStore, applyMiddleware} from "redux";
import rootReducer from "../reducers/rootReducer";
import thunk from "redux-thunk";
import logger from "redux-logger";
const initialState = {};
const store = createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
);
export default store;
还有我的 App.js
import React, {Component} from 'react';
import "../css/style.css";
import queryString from 'query-string';
import {connect} from "react-redux";
import PropTypes from "prop-types";
import {fetchUserData,fetchNewAlbums} from "../actions/index.js";
import SignInButton from "../components/SignInButton";
import SearchBar from "../components/SearchBar";
import MusicCards from "../components/Cards/MusicCards";
class App extends Component {
constructor(props){
super(props);
this.state = {
isShowAlbumsClicked:false
};
this.handleSignIn = this.handleSignIn.bind(this);
this.handleShowAlbumsClick = this.handleShowAlbumsClick.bind(this);
}
componentDidMount(){
let parsed = queryString.parse(window.location.search);
let accessToken = parsed.access_token;
if(!accessToken){
return;
}
this.setState({
accessToken:accessToken
})
this.props.fetchUserData(accessToken);
this.props.fetchNewAlbums(accessToken);
console.log(this.props.newAlbums);
}
handleSignIn(e){
e.preventDefault();
window.location=window.location.href.includes('localhost') ? 'http://localhost:8888/login':'https://something.herokuapp.com/login'
}
handleShowAlbumsClick(e){
this.setState({
isShowAlbumsClicked:!this.state.isShowAlbumsClicked
})
}
render(){
return (
<div className="app">
{this.props.userData ?
<div>
<h1 style={{'fontSize': '40px', 'marginTop':'1%'}}>
Welcome {this.props.userData.display_name} to Find Your Music
</h1>
<SearchBar/>
{this.state.isShowAlbumsClicked ?
<div>
<MusicCards/>
</div> : <h2 onClick={this.handleShowAlbumsClick}>Show</h2>
}
</div> : <SignInButton handleSignIn={this.handleSignIn}/>
}
</div>
);
}
}
App.propTypes={
fetchUserData:PropTypes.func.isRequired,
fetchNewAlbums:PropTypes.func.isRequired,
userData:PropTypes.object,
newAlbums:PropTypes.object
}
const mapStateToProps = (state) =>{
return{
userData: state.userData.data,
newAlbums: state.newAlbum.albums
};
};
const mapDispatchToProps = {
fetchUserData,
fetchNewAlbums
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
所以看起来你已经安装了 redux-thunk 但你没有使用它。 我看到您通过 thunk 在创建商店中应用中间件,这很好。
在您的动作创建器中尝试类似的操作。
export const fetchNewAlbulms = (accessToken) => async dispatch => {
const response = await fetch('https://api.spotify.com/v1/browse/new-releases?limit=5',{headers:{'Authorization': 'Bearer ' + accessToken}})
dispatch({
type:"FETCH_NEW_ALBUMS",
payload:albums.albums.items
})
}
或者这个(同样的事情)
export const fetchNewAlbulms = (accessToken) => {
return async dispatch => {
const response = await fetch('https://api.spotify.com/v1/browse/new-releases?limit=5',{headers:{'Authorization': 'Bearer ' + accessToken}})
dispatch({
type:"FETCH_NEW_ALBUMS",
payload:albums.albums.items
})
}
}
您的减速器不需要任何更新。
这将等待调度,直到它得到响应。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.