简体   繁体   English

useEffect 钩子依赖没有得到更新

[英]useEffect hook dependency not getting updated

I am making an API call inside useEffect hook as follows:我正在 useEffect 钩子内进行 API 调用,如下所示:

useEffect(() => {
fetchPatientsStartAsync(patientListUrl);
}, [patientListUrl]);

In my code I also have two other state variables and a method as follows:在我的代码中,我还有另外两个状态变量和一个方法,如下所示:

 const [d, setD] = useState(new Date());
 const [patientListUrl, setUrl] = useState(`${baseUrl}api/patient/list?date=${getDate()}`);

 function getDate() {
  return new Date(d.getFullYear(),d.getMonth(),d.getDate())
 }

I am using a date picker library for updating the 'd' (date).我正在使用日期选择器库来更新“d”(日期)。 Whenever the date changes I call setUrl and am expecting the useEffect hook to run again.每当日期更改时,我都会调用 setUrl 并期待 useEffect 钩子再次运行。 The call goes like this:调用是这样的:

    <DatePicker
        onChange={onChange}
        value={d}
        clearIcon={null}
    />
    const onChange = dt => {
     setD(dt);
     setUrl(`${baseUrl}api/patient/list?date=${getDate()}`);
    };

But this is not updating my 'patientListUrl' variable.但这并没有更新我的 'patientListUrl' 变量。 What is it that am doing wrong here?在这里做错了什么?

I simply want the API call to happen again with the updated 'patientListUrl'.我只是希望 API 调用通过更新的“patientListUrl”再次发生。

The problem is setD is async function so when you call getDate d isn't updated so you should pass dt to getDate function to get updated URL.问题是 setD 是异步函数,因此当您调用 getDate 时,d 不会更新,因此您应该将 dt 传递给 getDate 函数以获取更新的 URL。

function getDate(dt) {
  return new Date(dt.getFullYear(),dt.getMonth(),dt.getDate())
}
const onChange = dt => {
 setD(dt);
 setUrl(`${baseUrl}api/patient/list?date=${getDate(dt)}`);
};

The problem occurs because your state has not yet had the chance to update before you call the getDate function.出现问题是因为在调用getDate函数之前,您的状态还没有机会更新。 To remedy this, you could just avoid saving the URL to the state, and constructing it in your effect instead.为了解决这个问题,您可以避免将 URL 保存到状态,而是在您的效果中构建它。 The dependency to your effect would then be the date itself, like so:对您的影响的依赖将是日期本身,如下所示:

function getDate(d) {
    return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}

const Component = props => {
    const [d, setD] = useState(new Date());

    useEffect(() => {
        const patientListUrl = `${baseUrl}api/patient/list?date=${getDate(d)}`;
        fetchPatientsStartAsync(patientListUrl);
    }, [d]);

    const onChange = dt => {
        setD(dt);
    };

    return <DatePicker onChange={onChange} value={d} clearIcon={null}/>
}

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

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