[英]How to trigger an useEffect hook in React?
我正在尝试制作一个应用程序,它从用户那里接收产品的 ID,然后从数据库中找到产品并更新屏幕上的产品。 我通过使用useState
和输入框接收 ID。 调用GetProduct
组件,并通过Props
将 ID 传递给它。 它通过该 ID 获取产品(使用useEffect
)并返回该产品。
问题:
useEffect
在应用启动时(当 ID 仍为空时)获取产品一次,当 ID 更新时,产品不会再次更新。
应用程序.tsx:
function App() { const [id, setId] = useState("") const onChangeHandler = (event: { target: { value: React.SetStateAction<string> } }) => { setId(event.target.value) } return( <div className="App"> <input type="text" name="name" onChange={onChangeHandler} value={id} /> <GetProduct id={id}></GetProduct> </div> )
GetProduct
组件:
import { Product } from "../api/dto/product.dto" import productService from "../services/product.service" interface Props { id: string } export const GetProduct: React.FC<Props> = (props) => { const [product, setProduct] = useState<Product>() useEffect(() => { async function fetchOne() { const response = await productService.getOne(props.id) setProduct(response.data) } fetchOne() }, []) return ( <> <div> {product?.title}, {product?.description}, {product?.price} </div> </> ) }
您可以将props.id
添加到依赖数组,以便在 id 更改时重新运行。 有一个空的依赖数组使它只运行一次。
useEffect(() => { async function fetchOne() { const response = await productService.getOne(props.id) setProduct(response.data) } fetchOne() }, [props.id])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.