我现在正在学习使用 API、redux 和 thunk。我得到:
<块引用>未处理的拒绝(TypeError):Object(...) 不是函数
错误。
我的 api.js
是:
export const baseUrl = 'https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Coffee_/_Tea';
我的 receiptsAction.js
是:
import axios from 'axios';
import {baseUrl} from '../api';
export const loadRecipes = () => async(dispatch) => {
const drinksData = await axios.get(baseUrl());
dispatch({
type: "FETCH_RECIPES",
payload: {
drinks: drinksData.data,
}
})
}
我的 receiptsReducer.js
是:
const initState = {
drinks: {},
}
const receiptsReducer = (state=initState, action) => {
switch(action.type) {
case "FETCH_RECIPES":
return {
...state, drinks: action.payload.drinks
}
default:
return {...state}
}
}
export default receiptsReducer;
我的 Home.js
是:
import React, { useEffect } from 'react';
import {loadRecipes} from '../actions/receiptsAction';
import {useDispatch, useSelector} from 'react-redux';
const Home = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(loadRecipes())
}, [dispatch]);
return(
<div>
<p>Hello</p>
</div>
)
}
export default Home;
我的尝试:
App.js
中完全有效并且加载信息正常:const coctailHandler = async () => {
let url = "https://www.thecocktaildb.com/api/json/v1/1/filter.php?c=Coffee_/_Tea";
const coctails = await axios.get(url);
console.log(coctails.data.drinks);
}
const initState = {drinks: {drinks: []},}
。还尝试在 reducer 中使用 payload: {drinks: drinksData.data.drinks}
编写操作 const initState = {drinks: []}
。将不胜感激任何帮助!
答案 0 :(得分:1)
您正在调用 baseUrl
就好像它是一个函数,但它似乎只是一个 string
常量。
await axios.get(baseUrl())
应该是
await axios.get(baseUrl)