[英]React.useEffect not running on re-render
我有以下組件調用 API (googleSearch()),並使用結果將它們傳遞給子組件。
問題是當 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>
);
您需要將string_date
傳遞到效果的依賴數組中。
React.useEffect(() => {
...
}, [string_date])
這使得效果在string_date
的值發生變化時運行,包括在掛載時,並且它以string_date
的新值運行
空的 dep 數組只會在掛載時運行,根本不提供數組會在每次渲染時運行效果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.