繁体   English   中英

reactjs 在需要时不更新 state

[英]reactjs not updating state when needed

我有一些输入字段必须在调用onCompleteOrder之前设置。 我使用useState存储错误,我需要程序继续查看哪些字段未设置,因此将错误保留在errors state 中。 如果errors state 不为空,则阻止调用该 function。 问题是 state 是在单击按钮后更新的,我知道这必须使用useEffect挂钩来处理,我该如何正确地做到这一点?

const OrderModal = (props) => {

    const [errors, setErrors] = React.useState([])
    const [selectedFile, setSelectedFile] = React.useState(oldFile)
    const [startDate, setStartDate] = React.useState(new Date());
    const [endDate, setEndDate] = React.useState(null);
    const { isAuthenticated, user } = useAuth0();


    React.useEffect(() => {
        let currentErrors = errors.map(err => err.type)
        let newErrors = []
        if (!isAuthenticated && currentErrors.includes("authentication")) newErrors.push({ type: "authentication", message: "You must log in before creating an order!." })
        if (!selectedFile && currentErrors.includes("image")) newErrors.push({ type: "image", message: "Please select an image." })
        if (!startDate && currentErrors.includes("startDate")) newErrors.push({ type: "startDate", message: "Please select a start date." })
        if (!endDate && currentErrors.includes("endDate")) newErrors.push({ type: "endDate", message: "Please select an end date." })
        setErrors(newErrors)
    }, [isAuthenticated, selectedFile, startDate, endDate])

}

const renderInputErrors = () => {
        return (
            <>
                {errors.length > 0 &&
                    errors.map(e => {
                        return (
                            <CAlert color="danger" dismissible>
                                {e}
                            </CAlert>
                        )
                    })
                }
            </>
        )
    }

const onCompleteOrder = () => {
        if (errors.length > 0) return
        // complete the order if all fields are set. 
    }

暂无
暂无

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

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