[英]i am trying to display data from an external api, if someone can please help me to fix the issue in my code
this is the error message i am getting TypeError: undefined is not an object (evaluating 'drinkList.drinks[0]')这是我收到的错误消息 TypeError: undefined is not an object (evaluating 'drinkList.drinks[0]')
can you help me please fix the error and give me some solution so that i can use the app to fetch data from the external api?你能帮我修复错误并给我一些解决方案,以便我可以使用该应用程序从外部api获取数据吗?
this is my drink.js code:这是我的 Drink.js 代码:
import React, { useEffect, useState } from "react";
import axios from "axios";
import Drinks from "./Drinks";
function Home() {
const [drinkName, setDrinkName]= useState([]);
const [drinkList, setDrinkList] = useState([]);
const drinksURL = `https://www.thecocktaildb.com/api/json/v1/1/search.php?s=${drinkName}`;
const handleChangeDrink= e => {
setDrinkName(e.target.value);
}
const getDrink = () => {
axios
.get(drinksURL)
.then(function (response) {
setDrinkList(response.data);
console.log(drinksURL);
})
.catch(function (error) {
console.warn(error);
});
};
return (
<main className="App">
<section className="drinks-section">
<input
type="text"
placeholder="Name of drink (e.g. margarita)"
onChange={handleChangeDrink}
/>
<button onClick={getDrink}>Get a Drink Recipe</button>
<Drinks drinkList={drinkList} />
</section>
</main>
);
}
export default Home;
this is my Drink.js code:这是我的 Drink.js 代码:
import React from "react";
function Drinks({ drinkList }) {
if (!drinkList) return <></>;
return (
<section className="drinkCard">
<h1>{drinkList.drinks[0].strDrink}</h1>
</section>
);
}
export default Drinks;
Couple of problems here...这里有几个问题......
drinkName
is initialised as an array but it appears to be expecting a string drinkName
被初始化为一个数组,但它似乎需要一个字符串drinksUrl
is never updated drinksUrl
永远不会更新Some easy fixes一些简单的修复
const [drinkName, setDrinkName]= useState(null) // initialise as null
const [drinkList, setDrinkList] = useState([])
// don't include the "s" parameter here
const drinksURL = "https://www.thecocktaildb.com/api/json/v1/1/search.php"
const getDrink = () => {
// pass drinkName as a param
axios.get(drinksURL, {
params: { s: drinkName }
}).then(({ data }) => {
setDrinkList(response.data)
}).catch(console.warn)
}
and in Drink.js
在
Drink.js
function Drinks({ drinkList }) {
// check the array length
return drinkList.length && (
<section className="drinkCard">
<h1>{drinkList.drinks[0].strDrink}</h1>
</section>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.