當我運行此代碼時,它只會重復執行視窗提示“您使用什么貨幣?”,即使我輸入了有效貨幣。我對 js 很陌生,如果這真的很簡單,我很抱歉
import React from "react"
function Product(props) {
const MoreInfo = () => {
alert(props.product.description);
}
const UserCurrency = window.prompt("What currency do you use?")
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: UserCurrency,
})
return (
<div>
<h2>{props.product.name}</h2>
<p>{formatter.format(props.product.price)}</p>
<button onClick={MoreInfo}>More Info</button>
</div>
)
}
export default Product
uj5u.com熱心網友回復:
你需要了解 react hooks,在這種情況下:useState 和 useEffect
import { useState, useEffect } from 'react'
function Product(props) {
const [userCurrency, setUserCurrency] = useState(null)
useEffect(() => {
const uc = window.prompt("What currency do you use?")
setUserCurrency(uc)
}, [])
const MoreInfo = () => {
alert(props.product.description);
}
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: UserCurrency,
})
return (
<div>
<h2>{props.product.name}</h2>
<p>{formatter.format(props.product.price)}</p>
<button onClick={MoreInfo}>More Info</button>
</div>
)
}
export default Product
使用 useEffect 時,如果您將依賴項的空陣列作為第二個引數傳遞,則代碼將僅在組件安裝時運行一次。
請閱讀檔案,因為這個解釋遠遠不足以理解這里的利害關系
https://reactjs.org/docs/hooks-effect.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/338318.html
標籤:javascript 反应
上一篇:如何使用反應鉤子形式驗證陣列?
下一篇:使用標簽索引遍歷div元素
