如何在React中触发使用效果钩?
我正在尝试制作一个从用户接收产品ID的应用程序,然后从数据库中找到产品并在屏幕上更新产品。我通过使用usestate
和一个输入框接收ID。 getProduct
组件被调用,ID通过props
传递给它。它通过该ID获取产品(使用useffect
)并返回该产品。
问题:useeffect
在应用程序启动时(ID仍然为空时)以及ID更新时,将产品获取一次产品不会再次更新。
app.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:
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>
</>
)
}
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. I receive the ID by using an useState
and an input box. The GetProduct
component gets called, and the ID is passed to it through Props
. It fetches the product by that ID (using an useEffect
) and returns that product.
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.
App.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:
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>
</>
)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将
props.id
添加到依赖项数组中,以便在ID更改上重新运行。拥有一个空的依赖性数组只能运行一次。You can add
props.id
to dependency array so it would rerun on id change. Having an empty dependency array makes it run only once.