useSelector() 不会在更新时重新渲染组件

时间:2021-05-04 18:22:37

标签: reactjs redux react-redux

我有一个呈现患者信息的功能组件。在组件中,useEffect 钩子中正在调度 3 个动作,如下所示。每个操作都在发出一个异步网络请求。

useEffect(()=>{
        dispatch(fetchInpatient(patient_id));
        dispatch(fetchAllDoctors());
        dispatch(fetchVacantRooms());
    }, []);

我也像这样使用 useSelector 获取状态:

    const inpatient = useSelector(state => state.inpatient.inpatient);
    const doctors = useSelector(state => state.doctors.doctors);
    const vacantRooms = useSelector(state => state.vacantRooms.vacantRooms);

我的返回代码取决于这 3 个获取的状态。所以,它看起来像这样:

if(inpatient && doctors && vacantRooms){
        //render user info
}
else{
        //render loading icon
}

现在,最初的 inpatientsdoctorsvacantRooms 填充为默认状态或以前的状态。但是当所有动作都被调度并且状态被更新时,useSelector 不会重新渲染我的组件,所以它会显示之前患者的信息,直到我手动刷新页面。解决这个问题的方法是什么?我究竟做错了什么?
这些是我的减速器:

export default (state = {} , action) => {
    switch(action.type){
        case 'FETCH_INPATIENT':
            return {...state , inpatient: action.payload};
        default:
            return state;
    }
}
export default (state = {} , action) => {
    switch(action.type){
        case 'FETCH_ALL_DOCTORS':
            return {...state , doctors: action.payload};
        default:
            return state;
    }
}
export default (state = {} , action) => {
    switch(action.type){
        case 'FETCH_VACANT_ROOMS':
            return {...state , vacantRooms: action.payload};
        default:
            return state;
    }
}

所有这些都在单独的文件中。我的 reducers/index 是这样的:

import{ combineReducers } from 'redux';
import inpatientsReducer from './inpatientsReducer';
import inpatientReducer from './inpatientReducer';
import allDoctorsReducer from './allDoctorsReducer';
import vacantRoomsReducer from './vacantRoomsReducer';

export default combineReducers({
    inpatients: inpatientsReducer,
    inpatient: inpatientReducer,
    doctors: allDoctorsReducer,
    vacantRooms: vacantRoomsReducer
});

我的 fetchInpatient(id) 操作创建者如下:

export const fetchInpatient = (inpatient_id) => {
    return async (dispatch) => {
        const response = await axios.post('http://localhost:3001/api/inpatients/display' , {inpatient_id});
        dispatch({
            type: 'FETCH_INPATIENT',
            payload: response.data
        })
    }
}

1 个答案:

答案 0 :(得分:1)

如果您确定其他函数工作正常,请将 shallowEqual 传递给 useSelector 的第二个参数:

import {
  useSelector,
  shallowEqual,
  ...
} from 'react-redux'
...
const inpatient = useSelector(state => state.inpatient.inpatient, [shallowEqual]);
const doctors = useSelector(state => state.doctors.doctors, [shallowEqual]);
const vacantRooms = useSelector(state => state.vacantRooms.vacantRooms, [shallowEqual]);

你可以在这里找到更多关于 redux hooks 的信息: Redux hooks