簡體   English   中英

未獲取數據(React-redux)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM