为什么每次组件重新渲染时 useEffect 都会运行?

时间:2021-03-26 12:25:06

标签: javascript reactjs redux use-effect

在我的主页组件(我称之为主页!)我使用 Cards.JS 组件,它具有如下代码所示的 posts 属性。

const Home = () => {
  const dispatch = useDispatch()
  const isLoading = useSelector(state => state.isLoading)
  const currentPage = useSelector((state) => state.idFor.currentPageHome)
  const homePosts = useSelector((state) => state.posts)
  useEffect(() => {
    dispatch(setIsLoading(true))
    dispatch(getAllPosts(currentPage))
  }, [dispatch, currentPage])
  return (
    isLoading ? (
      <Loader type="ThreeDots" color="#000000" height={500} width={80} />
    ) : (
      <Cards posts={homePosts} setCurrentPage={setCurrentPageHome} currentPage={currentPage} pageName={"LATEST"} />
    )
  )
}

Cards.Js 如下

const Cards = ({ posts, setCurrentPage, currentPage, pageName }) => {

  console.log('Cards.JS called', posts);
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(setIsLoading(false))
  })

  const handleNextPage = () => {
    dispatch(setIsLoading(true))
    dispatch(setCurrentPage(currentPage + 1))
  }
  const handlePreviousPage = () => {
    dispatch(setIsLoading(true))
    dispatch(setCurrentPage(currentPage - 1))
  }

  return (
    <div className="container">
      <h4 className="page-heading">{pageName}</h4>
      <div className="card-container">
        {
          posts.map(post => <Card key={post._id} post={post} />)
        }
      </div>
      <div className="page-div">
        {currentPage !== 1 ? <span className="previous-page" onClick={handlePreviousPage}>&lt;</span>
          : null}
        <span className="next-page" onClick={handleNextPage}>&gt;</span>
      </div>
    </div>
  )
}

我的问题: 当我回到主页时,每次都会调用 useEffect 并向后端请求相同的数据,这些数据已经在 Redux 商店中可用。

提前致谢:)

1 个答案:

答案 0 :(得分:3)

useEffect 将在每次组件重新渲染时运行。

诀窍是,它需要第二个参数:要“监视”的变量数组。如果该数组中的任何变量发生变化,它将运行。

如果您传递一个空数组,它最初只会运行一次,并且无论您的组件重新渲染多少次都不会再次运行。

useEffect(() => {
  dispatch(setIsLoading(false))
}, [])