问题描述
我正在使用 React Admin userRedirect 钩子,并且我正在重定向到作为组件的“页面”。有没有办法将数据传递到我重定向到的页面/组件? 我尝试了这个并观察了以下内容。
const PublicPage = (props) => {
console.log('data: ' + props.data);
return(
<Card>
<Title title="Public Page" />
<CardContent>
This is a public page. + {props.data}
</CardContent>
</Card>
)
}
如果我这样做:redirect('/public',{data:'this is some data'}),控制台日志显示'data: undefined'并且没有显示任何数据。
这对 RA 可行吗?感谢您提出的任何建议。
基督徒
解决方法
您可以使用查询字符串(例如“/public?foo=bar”)重定向到某个位置,然后从您的 PublicPage 组件中读取该查询字符串。
或者,您可以使用位置 state - 由 react-router 提供的某种数据容器。 useRedirect
不支持此操作,但手动操作并不难:
import { useHistory } from 'react-router-dom';
const useRedirectToPageWithState = () => {
const history = useHistory();
return useCallback((pathname,state) => {
history.push({
pathname,state
})
},[history]);
}
然后在您的 PublicPage 组件中,您可以使用 useLocation 读取位置状态:
const PublicPage = () => {
const { state: data } = useLocation();
// now data contains what you passed to the page