我正在嘗試創建一個具有收藏功能的應用程序。該功能實際上有效,但僅在第二次單擊后才有效。編輯其他信息:第一次單擊時,應用程序嘗試將信息發送到我的數據庫,但信息不完整。它只是發送我的初始值。第二次單擊時,它最終會附加其他所需值并保存到數據庫中。我對鉤子還很陌生,所以請隨意評論我的代碼可以使用的任何改進。這是我的 React 組件,它負責處理所有事情。import React, { useState, useEffect } from 'react';import { Button } from 'react-bootstrap';const ItemInfo = (props) => { const [item, setItem] = useState([]); const [ favorite, setFavorite ] = useState({favoritable_type: 'Item', favoritor_type: 'User' }) useEffect(() => { fetch(`/items/${props.match.params.id}`) .then((response)=>{ if(response.status === 200){ return(response.json()) } }) .then((item) => { setItem(item); }) }, []); const createFavorite = (data) => { fetch(`/favorites`, { body: JSON.stringify(data), headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': props.token }, method: 'POST' }) .then((resp) => { if (resp.ok) { setFavorite({}) alert('This items has been favorited!') } }) .catch((err) => { if (err) { console.log(err) } }) } const handleFavorite = () => { const value = { favoritor_id: props.current_user.id, favoritable_id: item.id } setFavorite(favorite => ({...favorite, value})); createFavorite(favorite) }如果我完全誠實的話,我不太確定這是在做什么。我遇到了一個有類似內容的答案,它似乎解決了控制臺中的問題,但沒有解決實際的 POST 嘗試。 useEffect(()=> { console.log(favorite) },[favorite])這一切似乎運作良好。 if (item === null) { return <div>Loading...</div> } return ( <React.Fragment> <Button onClick={ handleFavorite } >Favorite</Button> <h1>{item.title}</h1> <p>{item.body}</p> <p>{item.user_id}</p> </React.Fragment> );};export default ItemInfo;我嘗試將一些功能分離到不同的組件中,使用類組件重新創建它,但無法弄清楚。提前致謝!
onClick 函數需要兩次單擊才能更新狀態
慕婉清6462132
2023-08-05 19:40:29