【发布时间】:2020-02-28 03:43:26
【问题描述】:
我正在使用 react 钩子 useState 来控制一些 HTML。我遇到的问题是我无法更新状态。
它应该做的是当用户按下按钮时
<button type="button" onClick={(e)=>{add(product,category,quantity,cart)}}>Clickie</button>。它将触发add(),然后检查产品和数量是否为空。
到目前为止,它可以正常工作,但是我无法更新用于控制是否显示消息的状态。我有两个 useStates const [checkProduct, setCheckProduct] = useState(true)
const [checkQuantity, setCheckQuantity] = useState(true) 并且在我的函数内部,如果变量为空,我想将它们更改为 false。然而,这是行不通的改变。
如果变量为空,checkProduct 和 checkQuantity 应该为 false。否则,它们应该是真的。
const Header = (props) => {
const [product, setProduct] = useState('');
const [quantity, setQuantity] = useState('');
const [category, setCategory] = useState('');
const [checkProduct, setCheckProduct] = useState(true)
const [checkQuantity, setCheckQuantity] = useState(true)
let cart = false;
const a = []
for(let x in props.cat)a.push(x)
const add = (product,category,quantity,cart) =>{
console.log(checkProduct+' ' +checkQuantity)
if(product===''){
setCheckProduct(false)
}
if(quantity===''){
setCheckQuantity(false)
}
if(checkProduct && checkQuantity===true){
props.add(product,category,quantity,cart)
setCheckQuantity(true)
setCheckProduct(true)
}
console.log(checkProduct+' ' +checkQuantity)
setProduct('')
setQuantity('')
}
return(
<div id='header'>
<input type="text" value={product} onChange={(e)=>setProduct(e.target.value)}/>
{!checkProduct ?<span>Please enter an item</span>:null}
<select id='category' defaultValue={'default'} onChange={(e)=>setCategory(e.target.value)}>
<option value='default'>Please choose a category</option>
{a.map((x,index)=><option value={x} key={index}>{x}</option>) }
</select>
<input id='quantity' type="number" value={quantity} onChange={(e)=>setQuantity(e.target.value)}/>
{!checkQuantity ? <span>Please enter an quantity</span>:null}
<br/>
<button type="button" onClick={(e)=>{add(product,category,quantity,cart)}}>Clickie</button>
</div>)
}
export default Header;
【问题讨论】:
标签: reactjs