简体   繁体   中英

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.

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.


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.

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

An empty dep array will only run on mount, and not providing an array at all will run the effect on every render

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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