我有一个呈现病人信息的功能组件,在这个组件中,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
}
现在,inpatients
、doctors
和vacantRooms
最初是用默认状态或以前的状态填充的。但是当所有的操作都被分派并且状态被更新时,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
})
}
}
3条答案
按热度按时间muk1a3rh1#
如果您确定其他函数可以正常工作,请将shallowEqual传递给useSelector的第二个参数:
您可以在这里找到有关redux钩子的更多信息:Redux hooks
gorkyyrv2#
具有相依性数组
[]
的useEffect
拦截只会在元件第一次挂载时执行一次。您的获取操作依赖于
patient_id
变量,因此您应该在依赖项中包含patient_id
。wmomyfyw3#
对我来说是
shallowEqual
没有[]