1.history:
history
是用于在 React 组件中进行页面导航和管理历史记录的工具。通过 history
,你可以在不同页面之间进行跳转、监听路由变化等操作。在 Umi 中,通常会使用 history
对象来实现页面的跳转和路由相关的操作。示例代码可能如下所示:
发:
import { history } from '@umijs/max';
// 在某个事件触发时跳转到指定页面,并传递参数
const handleClick = () => {
const params = {
id: 123,
name: 'example',
};
history.push({
pathname: '/another-page',
query: params,
});
};
收:
import { useLocation } from 'umi';
const AnotherPage = () => {
const location = useLocation();
const params = location.query;
console.log(params); // { id: 123, name: 'example' }
return (
<div>
<h1>Another Page</h1>
<p>ID: {params.id}</p>
<p>Name: {params.name}</p>
</div>
);
};
很少使用字符串拼接的传递参数:
发:
import { history } from '@umijs/max';
// 在某个事件触发时跳转到指定页面,并传递参数
const handleClick = () => {
const id = 123;
history.push(`/another-page/${id}`);
};
收:
import { useParams } from 'umi';
const AnotherPage = () => {
const params = useParams();
console.log(params.id); // 123
return (
<div>
<h1>Another Page</h1>
<p>ID: {params.id}</p>
</div>
);
};
2.useModel:
useModel
是一个用于在函数式组件中获取和操作 Umi Model 的钩子函数。在 Umi 中,Model 是一种用于管理数据和状态的概念,可以帮助你更好地组织和管理应用程序的数据流。通过 useModel
,你可以在函数式组件中轻松地访问和操作 Model 中的数据和方法。示例代码可能如下所示:
import { useModel } from '@umijs/max';
const MyComponent = () => {
const { data, loading, error, fetchList } = useModel('example');
useEffect(() => {
// 在组件加载时获取数据
fetchList();
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
<h1>Example Data:</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};