我可以看到在正文標簽 POST 方法中添加了正確的資料,但在最終 url 中只添加了 id。難道我做錯了什么?
以下是我得到的輸出,資料應該像 id:3,但在隨后的 Post 中,唯一的 id 被添加了。
{
id: "3",
title: "Greek Salad",
ingredients: [
"1 Onion",
"1 Block of Feta",
"Olives",
"Tomatoes",
"Olive Oil"
],
method: "Lorem ipsum dolor, sit amet consectetur adipisicing elit. Esse minima ex rem quis similique eum ratione quaerat, voluptas molestias ut repudiandae delectus voluptates. Eius esse at tenetur ab accusamus excepturi?",
cookingTime: "35 minutes"
},
{
id: "lXOYU8C"
},
{
id: "IacXVJs"
},
我正在使用以下鉤子進行 get& post 方法。
const useFetch = (url, method="GET") => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState(null);
const [option, setOptions] = useState(null)
const PostData = (info)=>{
setOptions({
method:"POST",
header:{
"Content-Type":"application/json"
},
body : JSON.stringify(info)
})
}
const fetchData = async (fetchOptions) => {
console.log("fetchOptions :",fetchOptions)
try {
setIsPending(true);
const response = await fetch(url,{...fetchOptions});
const databyresponse = await response.json();
setIsPending(false);
setData(databyresponse);
setError(null);
} catch (e) {
setIsPending(false);
console.log("error", e);
setError(e);
}
};
useEffect(() => {
if(method == "GET"){
fetchData();
}
if(method == "POST" && option){
fetchData(option);
}
}, [url,option,method]);
return { data, isPending, error, PostData };
};
export default useFetch;
這就是我如何呼叫我的 post 方法。
const {data, isPending, error, PostData } = useFetch("http://localhost:3000/recipes", "POST");
const [input, setInput] = useState({
title: "",
cookingTime: "",
method: "",
});
const [ingtext, setIngtext] = useState("");
const [ingredients, setIngredients] = useState([]);
const IngredientInput = useRef(null);
const onSubmithandler = (e) => {
console.log("submitted");
e.preventDefault();
console.log({input,ingredients})
let title = input.title;
let cookingTime = input.cookingTime;
let method = input.method;
PostData({title,cookingTime,method,ingredients})
};
uj5u.com熱心網友回復:
本來應該是:
setOptions({
methods:"POST",
header: {
"Content-Type": "application/json"
},
body: JSON.stringify(info)
})
失蹤s的methods是罪魁禍首。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397971.html
上一篇:HTML(Metro4)和GoogleSheets,異步加載資料
下一篇:將文章的文本方向從左到右更改
