简体   繁体   English

React Hooks,useState:handleSubmit 中的条件被忽略

[英]React Hooks, useState: Conditional in handleSubmit is being ignored

I have a function which takes the input from the form and runs the some method on the Array prototype, and I am then changing state in the isInAPI && wasAPICallMade (i've inserted the data in a code snippet) essentially if I should be getting something either way as the wasAPICallMade state is getting updated, but it's not.我有一个函数,它从表单中获取输入并在 Array 原型上运行some方法,然后我在isInAPI && wasAPICallMade更改状态(我已将数据插入到代码片段中)基本上如果我应该得到随着wasAPICallMade状态的更新,无论哪种方式,但事实并非如此。

What am I doing wrong?我究竟做错了什么?

 indgredients[{ id: 1, name: 'Hemp Protein' }, { id: 2, name: 'Avocado' }, { id: 3, name: 'Organic Maca' }, { id: 4, name: 'Organic Kale' }, { id: 5, name: 'Organic Coconut Water' }, { id: 6, name: 'Astragalus' }, { id: 7, name: 'Rhodiola' }, { id: 8, name: 'Other Spices' }, { id: 9, name: 'Green Coffee Beans' }, { id: 10, name: 'Organic Peach' }, { id: 11, name: 'Organic Seabuckthorn' }, { id: 12, name: 'Hijiki Seaweed' }, { id: 13, name: 'Organic Turmeric' }, { id: 14, name: 'Organic Ginger' }, { id: 15, name: 'Lime Juice' }, { id: 16, name: 'Bell Pepper' }, { id: 17, name: 'Organic Spinach' }, { id: 18, name: 'Organic Flax Seeds' }, { id: 19, name: 'Organic Goji Berry' }, { id: 20, name: 'Organic Chlorella' }, { id: 21, name: 'Organic Nutmeg' }, { id: 22, name: 'Kale' }, { id: 23, name: 'Tomato2' }, { id: 24, name: 'Organic Cucumber' }, { id: 25, name: 'Tamari' }, { id: 26, name: 'Organic Cacao' }, { id: 27, name: 'Chaga Mushroom' }, { id: 28, name: 'Raw Cashew' }, { id: 29, name: 'Lemon' }, { id: 30, name: 'Organic Cold Brew Coffee' }, { id: 31, name: 'Organic Sweet Cherry' }, { id: 32, name: 'Japanese Matcha Green Tea' }, { id: 33, name: 'Pink Himalayan Sea Salt' }, { id: 34, name: 'Organic Coconut' }, { id: 35, name: 'Watermelon' }, { id: 36, name: 'Organic Wheatgrass' }, { id: 37, name: 'Coconut Milk' }, { id: 38, name: 'Oats' }, { id: 39, name: 'Shiitake + Crimini Mushrooms' }, { id: 40, name: 'Organic Apple' }, { id: 41, name: 'Organic Camu Camu' }, { id: 42, name: 'Organic Zucchini' }, { id: 43, name: 'Organic Pea Protein' }, { id: 44, name: 'Chia Seed' }, { id: 45, name: 'Spinach' }, { id: 46, name: 'Organic Acerola Cherry' }, { id: 47, name: 'Butternut Squash Noodles' }, { id: 48, name: 'Sweet Potato' }, { id: 49, name: 'Galangal' }, { id: 50, name: 'Basil' }, { id: 51, name: 'Organic Raspberry' }, { id: 52, name: 'Black Garlic' }, { id: 53, name: 'Zucchini' }, { id: 54, name: 'Organic Peppermint' }, { id: 55, name: 'Raw Pumpkin Seed' }, { id: 56, name: 'Golden Figs' }, { id: 57, name: 'Papaya' }, { id: 58, name: 'Dulse Seaweed' }, { id: 59, name: 'Garlic' }, { id: 60, name: 'Madras Curry' }, { id: 61, name: 'Cordyceps Mushroom' }, { id: 62, name: 'Tomato' }, { id: 63, name: 'Reishi Mushroom' }, { id: 64, name: 'Cinnamon' }, { id: 65, name: 'Red Miso' }, { id: 66, name: 'Macadamia Nut' }, { id: 67, name: 'Organic Acai Berry' }, { id: 68, name: 'Raw Almond' }, { id: 69, name: 'Chickpea' }, { id: 70, name: 'Organic Mango' }, { id: 71, name: 'Organic Coconut Oil' }, { id: 72, name: 'Organic Pineapple' }, { id: 73, name: 'Organic Celery' }, { id: 74, name: 'Scallion' }, { id: 75, name: 'Organic Vanilla Bean' }, { id: 76, name: 'Ginger' }, { id: 77, name: 'Cauliflower' }, { id: 78, name: 'Raw Walnut' }, { id: 79, name: 'Organic Blueberry' }, { id: 80, name: 'Organic Date' }, { id: 81, name: 'Organic Banana' }, { id: 82, name: 'Rosemary' }, { id: 83, name: 'Vanilla Bean' }, { id: 84, name: 'Ginseng' }, { id: 85, name: 'Organic Strawberry' }, { id: 86, name: 'Carrot' }, { id: 87, name: 'Oregano' }, { id: 88, name: 'Lemon2' }, { id: 89, name: 'Organic Garbanzo Beans' }, { id: 90, name: 'Organic Blackberry' }, { id: 91, name: 'Organic Raw Almond Butter' }, { id: 92, name: 'Pecans' }, { id: 93, name: 'Organic Mulberry' }, { id: 94, name: 'Organic Pepper' }, { id: 95, name: 'Organic Hemp Seed' }, { id: 96, name: 'Organic Pumpkin' }, { id: 97, name: 'Organic Blue Majik' }, { id: 98, name: 'Organic Gluten-Free Oats' }, { id: 99, name: 'Organic Cardamom' }, { id: 100, name: 'Lemon Juice' },

import React, { useState } from 'react'
import Alert from '@material-ui/lab/Alert'

import TextField from '@material-ui/core/TextField'
import Grid from '@material-ui/core/Grid'

import { makeStyles } from '@material-ui/core/styles'

var useStyles = makeStyles((theme) => ({
    root: {
        '& > *': {
            margin: theme.spacing(1),
            width: '25ch',
        },
        submit: {
            color: 'red',
        },
    },
}))

var IngredientInput = ({ indgredients, products }) => {
    var [indgredients, setIngredients] = useState(indgredients)
    var [text, setText] = useState('')
    var [isInAPI, setIsInAPI] = useState(false)
    var [wasAPICallMade, setWastAPICallMade] = useState(false)

    function CheckIngredients(input) {
        if (indgredients.some((item) => item.name === input)) {
            setIsInAPI((prevState) => !prevState)
            console.log('isInAPI ', isInAPI)

            setWastAPICallMade((prevState) => !prevState)
            console.log('wasAPICallMade ', wasAPICallMade)
        }
    }

    function handleTextChange(e) {
        console.log('e', e.target.value)
        setText(e.target.value)
    }

    function handleSubmit(e) {
        e.preventDefault()
        CheckIngredients(text)
        setText('')
    }
    
    var classes = useStyles()

    return (
        <>
            <Grid container justify="center">
                <form onSubmit={handleSubmit} className={classes.root}>
                    <TextField
                        value={text}
                        onChange={handleTextChange}
                        id="outlined-basic"
                        label="Outlined"
                        variant="outlined"
                    />
                    <button type="submit" className={classes.submit}>
                        {' '}
                        Check Ingredient{' '}
                    </button>
                </form>
                {wasAPICallMade ? (
                    isInAPI ? (
                        <Alert severity="success">
                            This is a success alert — check it out!
                        </Alert>
                    ) : (
                        <Alert severity="error">
                            This is an error alert — check it out!
                        </Alert>
                    )
                ) : null}
            </Grid>
        </>
    )
}
export default IngredientInput

Update更新

Based on what Emile and Lanxion suggested I tried this:根据 Emile 和 Lanxion 的建议,我尝试了以下操作:

useEffect(() => {
    console.log('isInAPI in useEffect', isInAPI)
    console.log('wasAPICallMade in useEffect', wasAPICallMade)
}, [isInAPI, wasAPICallMade]) 

function CheckIngredients(input) {
    setWastAPICallMade(true)
    var found = indgredients.some((item) => item.name === input)

    console.log('found ', found)
    if (found) {
        setIsInAPI(true)
        console.log('isInAPI ', isInAPI)
    }
}

Now two questions with this change:现在有两个关于这个变化的问题:

I'm correct in understanding useEffect will fire on the initial render and everytime changes to those variables are made?我正确理解useEffect将在初始渲染时触发,并且每次更改这些变量时都会触发? If not, useEffect won't fire.如果不是,则 useEffect 不会触发。

So in the CheckIngredients function setWastAPICallMade(true) gets ignored?那么在CheckIngredients函数中setWastAPICallMade(true)被忽略了吗?

Also why doesn't var found = indgredients.some((item) => item.name === input) have the correct response???还有为什么var found = indgredients.some((item) => item.name === input)没有正确的响应???

function CheckIngredients(input) {
    setWastAPICallMade(true)
    var found = indgredients.some((item) => item.name === input)

    console.log('found ', found)
    if (found) {
        setIsInAPI(true)
        console.log('isInAPI ', isInAPI)
    }
}

Most likely, your state is being updated , but useState hook functions are asynchronous, so if you log the state right in the next line, it may not reflect the change immediately.最有可能的是,您的状态正在更新,但useState钩子函数是异步的,所以如果您在下一行记录状态,它可能不会立即反映更改。 If you would like to check the value of a specific state after change to it, you can use a useEffect hook with the second value as the state variable that you are watching.如果您想在更改后检查特定状态的值,您可以使用带有第二个值的useEffect钩子作为您正在观看的状态变量。

useEffect(() => {
    console.log('isInAPI ', isInAPI); 
    console.log('wasAPICallMade ', wasAPICallMade)
}, [isInAPI, wasAPICallMade])// This is be executed when "isinApi" or "wasAPICallMade" state changes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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