【问题标题】:Run useEffect only on submit仅在提交时运行 useEffect
【发布时间】:2021-08-18 16:27:15
【问题描述】:

我有这个功能组件-

    function ModelPredict({ model }) {
    const [predictionDate, setPredictionDate] = useState('')
    const [predictionValue, setPredictionValue] = useState('')
    const [isLoading, setIsLoading] = useState(false)

    useEffect(() => {
        const fetchPrediction = async () => {
            setIsLoading(true)
            const res = await fetch(`http://localhost:8000/api/predict/${model.id}/?`
                              + new URLSearchParams({pred_date: predictionDate}))
            const predictionValue = await res.json()
            setPredictionValue(predictionValue)
            setIsLoading(false)
        }

        if (predictionDate) fetchPrediction()
    }, [predictionDate, model])

    return (
        <div>
            <label>Select Prediction date: </label>
            <input type="date" name="date" value={predictionDate}
             onInput={e => setPredictionDate(e.target.value)} />
            <input type="submit" value="Submit"/>
            {isLoading && <p>Predicting ...</p>}
            {!isLoading && predictionValue && <p>Prediction: {predictionValue.prediction}</p>}
        </div >
    )
}

目前useEffect 将在每次输入日期时触发。
我希望useEffect 应该仅在单击提交按钮时运行。

一种方法是设置另一个状态 inpReady 并在 onSubmit 内部调用 setInpReady(true),然后在调用 fetchPrediction 之前检查内部 useEffect 是否 inpReady 为真。
有没有更好的办法?

【问题讨论】:

  • 或者你可以创建一个你在提交时调用的函数

标签: javascript reactjs


【解决方案1】:

我不知道我是否理解你的问题,但是这里需要 useEffect 吗?从 useEffect 中删除所有代码并将其全部放入 onSubmit 函数有什么问题?这将解决您的问题。

【讨论】:

    【解决方案2】:

    一个选项可以设置 isSubmmited 标志并将其用作 useEffect 中的依赖项:

    const [isSubmmited, setIsSubmitted] = useState(false)
    

    然后onSubmit调用setIsSubmmited(true)

    另一种选择是简单地让 onSubmit 在useEffect 中处理您想要的逻辑

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2023-02-15
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 2020-10-22
      • 1970-01-01
      • 2022-08-17
      • 2022-11-02
      相关资源
      最近更新 更多