我有一个功能组件,用于呈现患者的信息。在组件中,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
})
}
}
具有依赖数组[]
的useEffect
挂钩在首次安装组件时只运行一次。
您的fetch操作依赖于patient_id
变量,因此您应该将patient_id
包含在依赖项中。
如果您确定其他函数工作正常,请将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钩子的信息:Redux挂钩
对于没有[]
的我来说是shallowEqual
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);