在使用 React-Admin 开发时,如果在 Context 中存储全局信息,并在导航时更新 Context 数据,可能会遇到 "Warning: You cannot change `
当你在 React 应用中使用 React Router 时,通常会使用 BrowserHistory 来处理路由。React Router 不希望 history 对象的引用发生改变,否则会触发警告。
在 React-Admin 中,如果没有显式地传递 history 对象给 组件,React-Admin 会自动创建一个。当 Context 的值更新时,会导致 组件重新渲染,进而创建一个新的 history 对象,从而触发 React Router 的警告。
解决此问题的关键在于,为 React-Admin 提供一个稳定的 history 对象,避免每次 Context 更新都重新创建。
安装 history 库:
如果你的项目中还没有安装 history 库,需要先安装它:
npm install history # 或者 yarn add history
创建自定义 History 对象:
在应用的入口文件中,创建一个 BrowserHistory 实例,并将其传递给 组件:
import { createBrowserHistory } from "history";
import { Admin, Resource } from 'react-admin';
import { Dashboard } from './Dashboard';
import { authProvider } from './authProvider';
import { dataProvider } from './dataProvider';
import { ShowFoo } from './ShowFoo';
const history = createBrowserHistory();
const App = () => {
return (
);
};
export default App;在这个例子中,我们导入了 createBrowserHistory 函数,创建了一个 history 实例,并将其作为 history prop 传递给了 组件。
下面是一个完整的示例,展示了如何使用 Context 和自定义 History 对象:
import React, { createContext, useState, useContext } from 'react';
import { createBrowserHistory } from "history";
import { Admin, Resource, ListGuesser, EditGuesser } from 'react-admin';
import { Link, Typography } from '@mui/material';
const AppContext = createContext({
appData: {},
setAppData: () => {},
});
const MyMenuLink = ({ primaryText, to, leftIcon, sidebarIsOpen, onMenuClick, dense, foo }) => {
const { setAppData, appData } = useContext(AppContext);
cons
t clickHandler = (e) => {
const newAppData = {
...appData,
foo: foo,
};
setAppData(newAppData);
};
return (
{primaryText}
);
};
const PostList = () => (
);
const PostEdit = () => (
);
const history = createBrowserHistory();
const App = () => {
const [appData, setAppData] = useState({
foo: null,
});
const value = {
appData,
setAppData
}
return (
);
};
export default App;在这个例子中:
通过为 React-Admin 提供自定义的 history 对象,可以有效地解决 "Warning: You cannot change