我将在 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®ion=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;
<小时/>
但是,从 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®ion=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/