简体   繁体   English

React.useEffect 未在重新渲染时运行

[英]React.useEffect not running on re-render

I have the following component that makes a call to an API (googleSearch()), and using the results passes them to the child component.我有以下组件调用 API (googleSearch()),并使用结果将它们传递给子组件。

The problem is that when the props.date is updated externally, the console.log(search_date) prints the new date however the useEffect just re-uses the old result, and does not make a new API call.问题是当 props.date 在外部更新时, console.log(search_date)会打印新日期,但是useEffect只是重新使用旧结果,并且不会进行新的 API 调用。


export default function News(props) {

  var searchDate = moment(props.date, "YYYY-MM-DD HH:mm:ss");
  var string_date = searchDate.format("MMMM+DD+YYYY");
  var nice_date = searchDate.format("MMMM DD YYYY");

  const [search_results, updateSearch] = React.useState([]);

  console.log(search_date)


  React.useEffect(() => {
    googleSearch(string_date).then((response) => {
      if (response === "undefined" || response === undefined) {
        updateSearch([])
      } else {
        updateSearch(response.data.items)
      }
    });
  },[]);

  return (
    <React.Fragment>
      <Button>News For {nice_date}</Button>
      <GoogleTable data={search_results} date={props.date} />
    </React.Fragment>
  );

You need to pass string_date into the dependency array on the effect.您需要将string_date传递到效果的依赖数组中。

React.useEffect(() => {
   ...
}, [string_date])

That makes the effect run when the value of string_date changes, including on mount, and it runs with that new value of string_date这使得效果在string_date的值发生变化时运行,包括在挂载时,并且它以string_date的新值运行

An empty dep array will only run on mount, and not providing an array at all will run the effect on every render空的 dep 数组只会在挂载时运行,根本不提供数组会在每次渲染时运行效果

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

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