【发布时间】: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