
在使用 React-Admin 开发时,如果在 Context 中存储全局信息,并在导航时更新 Context 数据,可能会遇到 "Warning: You cannot change `
问题分析
当你在 React 应用中使用 React Router 时,通常会使用 BrowserHistory 来处理路由。React Router 不希望 history 对象的引用发生改变,否则会触发警告。
在 React-Admin 中,如果没有显式地传递 history 对象给
解决方案:传递自定义 History 对象
解决此问题的关键在于,为 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);
const 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;在这个例子中:
- 我们创建了一个 AppContext 用于存储全局数据。
- MyMenuLink 组件使用 useContext 获取 setAppData 函数,并在点击链接时更新 Context 数据。
- 创建了一个 history 对象并传递给了
组件。
注意事项
- 确保 history 对象在应用启动时只创建一次,并在整个应用生命周期内保持不变。
- 避免在组件内部创建 history 对象,否则每次组件渲染都会创建一个新的 history 对象,导致问题复现。
- 如果使用了其他的路由库,需要根据相应的文档创建和传递 history 对象。
总结
通过为 React-Admin 提供自定义的 history 对象,可以有效地解决 "Warning: You cannot change











