自定义 React-Admin 应用程序中的 useNavigate() 挂钩问题

问题描述 投票:0回答:1

我的 React-Admin 应用程序面临一个具有挑战性的问题。当我尝试在自定义登录组件 (

useNavigate()
) 中使用
MyLoginPage
挂钩时,出现以下错误:

[Route] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

有问题的行为: 该错误仅发生在

MyLoginPage
内,它被设置为 React-Admin 的
<Admin>
组件中的 loginPage 属性,这表明它本身应该具有路由上下文。

设置:

Shell 组件:充当 React-Admin 的

<Admin>
的包装器,用于 Firebase 身份验证状态处理。
MyLoginPage
组件:使用
useNavigate()
进行登录后重定向的自定义登录组件。 这是
MyLoginPage
中调用
useNavigate()
的片段:

MyLoginPage 组件

import { useNavigate } from "react-router-dom";
// ... other imports

const MyLoginPage = () => {
  const navigate = useNavigate(); // this line triggers the error
  // ... rest of the component
};

以下是

MyLoginPage
在应用程序结构中的使用方式:

应用程序组件

import { Admin } from "react-admin";
import MyLoginPage from "./MyLoginPage";
import { Shell } from "./Shell";

const App = () => {
  return (
    <Shell>
      <Admin loginPage={MyLoginPage} /* ... other props ... */>
        {/* ... resources ... */}
      </Admin>
    </Shell>
  );
};

尝试解决:

  • 确保
    MyLoginPage
    呈现为
    <Admin>
    的子级。
  • 检查了可能与 React-Admin 的路由器上下文冲突的其他
    <Router>
    实例。

我很困惑为什么

useNavigate()
MyLoginPage
中失去了上下文。这可能是组件安装顺序的问题吗?任何建议或见解将不胜感激!

javascript reactjs react-router-dom react-admin
1个回答
0
投票

我不是react-admin包的专家,但文档很清楚, 文档 admin-react 自定义挂钩 useLogin

in src/MyLoginPage.js

import * as React from 'react';
import { useState } from 'react';
import { useLogin, useNotify, Notification } from 'react-admin';

const MyLoginPage = ({ theme }) => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const login = useLogin();
    const notify = useNotify();

    const handleSubmit = e => {
        e.preventDefault();
        // will call authProvider.login({ email, password })
        login({ email, password }).catch(() =>
            notify('Invalid email or password')
        );
    };

    return (
        <form onSubmit={handleSubmit}>
            <input
                name="email"
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
            />
            <input
                name="password"
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
            />
        </form>
    );
};

export default MyLoginPage;

我认为这会自动重定向到您的内容。

没用

useNavigate()
钩子,它会自动添加到菜单项(我认为)

[用于在应用程序中使用自定义菜单项重定向到自定义路由][https://marmelab.com/react-admin/CustomRoutes.html#adding-custom-routes-to-the-menu]

告诉我是否有效。我很好奇。

© www.soinside.com 2019 - 2024. All rights reserved.