当我更改路线时,如何防止Reaction组件重新渲染?

2022-04-02 00:00:00 reactjs javascript react-router-dom

我有反应组件:allUsersList和userDetail。在第一个示例中,我获取所有用户并显示它们,通过单击每个用户,我更改了路线并转到第二个组件,但当我单击箭头返回浏览器时,第一个组件开始获取数据并再次重新呈现。您能告诉我如何防止它执行额外的重新渲染吗?

这是所有用户组件:

import React, {useEffect, useMemo} from 'react';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import {setAllUsers, setLoading, setPage} from '../redux/actions/actions';
import User from './User';
import '../styles/AllUsersList.css';

const AllUsersList = () => {
    const allUsers = useSelector(state => state.setAllUsersReducer);
    const page = useSelector(state => state.setPageReducer);
    const loading = useSelector(state => state.setLoadingReducer);
    const dispatch = useDispatch();
  

    const fetchAllUsers = () => {
       fetch(`${url}/${page}/15`)
            .then(res => res.json())
            .then(data => {
                dispatch(setAllUsers(data.list));
            })
            .catch(err => console.log('Error message: ', err))
    }

    useEffect(() => {
      fetchAllUsers();
    }, [page])

    const handleScroll = () => {
        dispatch(setPage());
    }

    window.onscroll = function () {
        if(window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight) {
            handleScroll();
        }
    }


    return (
        <div className="allUsersList">
            {
                allUsers ? (
                    allUsers.map((user, index) => (
                        <Link key={user.id} to={`/user/${user.id}`}>
                            <User name={user.name} lastName={user.lastName} prefix={user.prefix} title={user.title} img={user.imageUrl}/>
                        </Link>
                    ))
                ) : (
                    <div> Loading... </div>
                )
            }
        </div>
    )
}

export default AllUsersList;

以下是UserDetail组件:

import React, {useEffect} from 'react';
import {useParams} from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { setSelectedUser, removeUser, setSelectedUsersHistory } from '../redux/actions/actions';

export const UserDetails = () => {
    const selectedUser = useSelector(state => state.setSelectedUserReducer);
    const selectedUsersHistory = useSelector(state => state.setSelectedUsersHistoryReducer);
    const dispatch = useDispatch();
    const {userId} = useParams();
    const fetchUserDetails = () => {
        fetch(`${url}/${userId}`)
            .then(res => res.json())
            .then(data => {
                 dispatch(setSelectedUser(data));
              }
            )
            .catch(err => console.log('Error message: ', err))
    }

    useEffect(() => {
        if(userId && userId!=='') fetchUserDetails();
        
        return () => {
            dispatch(removeUser())
        }
    }, [userId])


    return (
        <div className="userDetails">
            {
                Object.keys(selectedUser).length === 0 ? (
                    <div>Loading...</div>
                ) : (
                    <div>{selectedUser.name}</div>
                )
            }
        </div>
    )
}

export default UserDetails;

这里是应用程序js,带有路径:

import React from 'react';
import AllUsersList from './components/AllUsersList';
import UserDetails from './components/UserDetails';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';

function App() {

  return (
    <div className="App">
      <Router>
        <Switch>
          <Route path="/" exact component={AllUsersList} />
          <Route path="/user/:userId" exact component={UserDetails} />
        </Switch>
      </Router>
 
    </div>
  );
}

export default App;

解决方案

您是否尝试过useMemo()?https://reactjs.org/docs/hooks-reference.html#usememo

它会在页面呈现后对您的页面进行备忘。这并不是每个渲染的保证,但根据我的经验,它通常是有效的。

相关文章