React:React Redux:Redux Thunk:未安装组件内存泄漏



我将尽我所能来表述这个问题,因为这非常令人困惑。我正在为我的应用程序状态使用redux。我使用redux-thunk来处理我对数据库的所有异步api调用。

我使用redux-thunk来处理我对数据库的异步POST api调用,以添加数据。我有一个父组件和一个嵌套组件。父组件包含我的数据网格,即AG React数据网格。我正在从包含我的数据网格的父组件切换到包含我将用于输入要存储到数据库的数据的表单的组件。异步调用完成后,我想路由回包含网格的原始视图(网格和输入表单嵌套在Parent组件中,我使用react router在两个视图之间切换(

一旦使用thunk调度异步调用,应用程序就会在实际调度的操作完成之前调用history.goBack((,就像在异步调用中一样。问题是,当路由回原始视图时,会导致这两个错误。

警告:无法对未安装的组件执行React状态更新。这是一个非操作,但它表明应用程序中存在内存泄漏。若要修复此问题,请取消useEffect清理函数中的所有订阅和异步任务

未捕获(承诺中(类型错误:rowData.map不是函数

我如何才能确保在thunk代码中完成操作,以便正确地重新渲染我的组件。

父组件代码

const store = configureStore();
const dispatch = useDispatch();
// selects the proper data from the redux store, this variable is used as row data for 
// AG Grid
const events = useSelector((state: AppState) => state.events.list);
const { path, url } = useRouteMatch();
const history = useHistory();
const [showBackBtn, setShowBackBtn = () => showBackBtn] = useState(false);
const goToAddEvent = () => {
history.push(`${url}/add-event`);
setShowBackBtn(true);
};
const backBtn = () => {
history.goBack()
setShowBackBtn(false);
}
const columns = [
{ field: "eventName", headerName: "Event name" },
{ field: "eventDate", headerName: "Event Date" },
{ field: "location", headerName: "Location" },
{ field: "startTime", headerName: "Start Time" },
{ field: "endTime", headerName: "End Time" },
];
//gets initial data, saves to the redux store
useEffect(() => {
const doGetEvents = async () => {
dispatch(getEventsAsyncFromDB());
};
doGetEvents();
//setShowBackBtn(!showBackBtn);
}, [dispatch, store]);

表单输入组件的代码

const AddEventComponent = () => {
const dispatch = useDispatch();
const history = useHistory();
const addEvent = (event: any) => {
event.preventDefault();
let eventData: Event = {
eventName: event.target[0].value,
location: event.target[1].value,
eventDate: event.target[2].value,
startTime: event.target[3].value,
endTime: event.target[4].value,
};
dispatch(addEventAsyncToDB(eventData));
history.goBack();
};

调用api将数据添加到数据库的Redux-Thunk代码

export const addEventAsyncToDB = (event: Event) => {
return async (dispatch: any) => {
dispatch(addingEventToDb);
return await addEvent(event).then((res) => {
dispatch(addedEventToDBAction(res?.data));
});
};
};

最后是使API调用的代码

export const addEvent = async (event: Event) => {
try{
const res = await axios.post(`${baseURI}/Events`, event);
return res;
}
catch(e){
console.log(e);
}
}

同样,API调用成功,问题是在实际API调用完成处理之前调用history.goBack((行,导致上述错误。请耐心等待,这是我能形成这个问题的最好方法

一个简单的解决方法是添加一个setTimeout函数,该函数将在向数据库添加数据完成后将页面路由回正确的路由

const addEvent = (event: any) => {
event.preventDefault();
let eventData: Event = {
eventName: event.target[0].value,
location: event.target[1].value,
eventDate: event.target[2].value,
startTime: event.target[3].value,
endTime: event.target[4].value,
};
dispatch(addEventAsyncToDB(eventData));
setTimeout(() => {
history.push('/app/events');
}, 3000);
};

最新更新