javascript - 为什么我无法加载 API?

标签 javascript reactjs redux

我将在 React 应用程序中使用 redux 调用电影 API。

在使用redux-thunk调用电影API的过程中, 在lib/THMb路径上调用callAPI函数时发生错误。

//movie_project/src/lib/THMb.js

import axios from 'axios';

const key = "xxxxxxx";
const url = `https://api.themoviedb.org/3/movie/now_playing?api_key=${key}&language=ko&page=1&region=KR`; 

export const callAPI = async () =>{
    await axios.get(`${url}`);
}
import {  handleActions } from "redux-actions";
import axios from "axios";
import * as movieAPI from '../lib/THMb';

// action types
const GET_MOVIES = 'movie/GET_MOVIES';
const GET_MOVIES_SUCCESS = 'movie/GET_MOVIES_SUCCESS';
const GET_MOVIES_FAILURE = 'movie/GET_MOVIES_FAILURE';

export const getMovies = () => async dispatch => {
    dispatch({ type: GET_MOVIES }); 
    try{
        const res = await movieAPI.callAPI(); // failed
        dispatch({
            type: GET_MOVIES_SUCCESS, // 요청 성공
            payload: res.data.results, // API 요청 결과 값
        })
    }catch(e){
        dispatch({
            type: GET_MOVIES_FAILURE, // 요청 실패
            payload: e,
            error: true
        })
        throw e;
    }
}

const initialState ={
    movieList : [],
    error: null
}

const movie = handleActions(
    {
        [GET_MOVIES]: state => ({
            ...state,
            // loading..
        }),
        [GET_MOVIES_SUCCESS]: (state, action) => ({
            ...state,
            movieList: action.payload,
        }),
        [GET_MOVIES_FAILURE]: (state, action) => ({
            ...state,
            // loading...
        })
    },
    initialState
)

export default movie;

enter image description here

<小时/>

但是,从 getMovies 函数中调用 url 时不会发生错误。

export const getMovies = () => async dispatch => {
    dispatch({ type: GET_MOVIES }); // 요청의 시작을 알림.
    try{
        //const res = await movieAPI.callAPI(); // failed
        // success
        const res = await axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=xxxxx&language=ko&page=1&region=KR`);
        dispatch({
            type: GET_MOVIES_SUCCESS, // 요청 성공
            payload: res.data.results, // API 요청 결과 값
        })

为什么第一种情况会出现错误???

最佳答案

那是因为在第一种情况下您不会返回任何内容。你应该尝试这个:

export const callAPI = async () => {
    let res = await axios.get(`${url}`);
    return res;
}

希望这对您有用。

关于javascript - 为什么我无法加载 API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60088609/

相关文章:

javascript - ReactJS,将 prop 从父组件传递给子组件?

javascript - 使用水合物而不是从 react-dom 渲染时检测损坏的图像

javascript - 改变 redux-starter-kit 的 createSlice 中的状态

javascript - Vue 范围 : how to delay handling of @mouseover

已知脚本标签组合的 Javascript 正则表达式

javascript - 如何在鼠标悬停在另一图像上时更改图像

javascript - 使用引用字段更新 contentful 中的条目

javascript - 如何在 react 中为两个或多个事件添加一个事件监听器

reactjs - Redux Saga - 更新本地状态的回调

node.js - 在没有用户登录的情况下将项目添加到购物车 react.js 和 redux