使用useState

时间:2020-02-28 03:43:26

标签: reactjs

我正在使用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;

1 个答案:

答案 0 :(得分:1)

setState是异步的。它将首先在这里检查您的状况

if (checkProduct && checkQuantity === true) {...}

在您的setCheckProduct(false)和setCheckQuantity(false)生效之前。 您可以检查产品和数量本身,然后可以使用setState:

 const add = (product, category, quantity, cart) => {

    if (product && quantity) {
      props.add(product, category, quantity, cart);
      setCheckQuantity(true);
      setCheckProduct(true);
    }else{
      setCheckQuantity(false);
      setCheckProduct(false);
    }

    setProduct("");
    setQuantity("");
};