简体   繁体   English

如何在 React 中触发 useEffect 钩子?

[英]How to trigger an useEffect hook in React?

I am trying to make an app that receives an ID for a product from the user, then finds the product from the database and updates the product on the screen.我正在尝试制作一个应用程序,它从用户那里接收产品的 ID,然后从数据库中找到产品并更新屏幕上的产品。 I receive the ID by using an useState and an input box.我通过使用useState和输入框接收 ID。 The GetProduct component gets called, and the ID is passed to it through Props .调用GetProduct组件,并通过Props将 ID 传递给它。 It fetches the product by that ID (using an useEffect ) and returns that product.它通过该 ID 获取产品(使用useEffect )并返回该产品。
The problem:问题:
The useEffect fetches the product once when the app starts (when the ID is still empty), and when the ID gets updated, the product won't update again. useEffect在应用启动时(当 ID 仍为空时)获取产品一次,当 ID 更新时,产品不会再次更新。
App.tsx:应用程序.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 Component: 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> </> ) }

You can add props.id to dependency array so it would rerun on id change.您可以将props.id添加到依赖数组,以便在 id 更改时重新运行。 Having an empty dependency array makes it run only once.有一个空的依赖数组使它只运行一次。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM