javascript React Router -Notebook和Note组件的嵌套路由

wwwo4jvm  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(125)

我想创建一个Notebook应用程序,其中有一个笔记本列表,如“数学”和“科学”。当我选择其中一个笔记本时,我希望显示所选笔记本中的笔记列表。然后,当我单击某个特定的笔记时,我希望打开该笔记并在一个单独的组件中显示其内容,在该组件中我可以继续记笔记或编辑现有的笔记。
我已经为这个项目创建了单独的NotebookListNotebookNote组件。
我目前正在使用React Router,在配置组件和路由结构以实现此功能时遇到了问题。
以下是我目前掌握的信息:
NotebookList.js

import { Link } from 'react-router-dom';

const NotebookList = () => {
  return (
    <div>
      <h1>Notebooks</h1>
      <ul>
        <li><Link to="/notebook/mathematics">Mathematics</Link></li>
        <li><Link to="/notebook/science">Science</Link></li>
        {/* Add more notebook options here */}
      </ul>
    </div>
  );
};

export default NotebookList;

Notebook.js

import { useParams } from 'react-router-dom';

const Notebook = () => {
  const { notebookId } = useParams();

  // Fetch the notes for the selected notebook using notebookId

  return (
    <div>
      <h1>Notebook: {notebookId}</h1>
      {/* Display the list of notes */}
    </div>
  );
};

export default Notebook;

Note.js

import { useParams } from 'react-router-dom';

const Note = () => {
  const { notebookId, noteId } = useParams();

  // Fetch the content of the selected note using notebookId and noteId

  return (
    <div>
      <h1>Note: {noteId}</h1>
      {/* Display the content of the note */}
    </div>
  );
};

export default Note;

App.js

import { BrowserRouter as Router, Route } from 'react-router-dom';
import NotebookList from './NotebookList';
import Notebook from './Notebook';
import Note from './Note';

const App = () => {
  return (
    <Router>
      <Route exact path="/" component={NotebookList} />
      <Route path="/notebook/:notebookId" component={Notebook} />
      <Route path="/notebook/:notebookId/note/:noteId" component={Note} />
    </Router>
  );
};

export default App;

我将感谢任何关于如何正确配置组件和路由结构以实现所需功能的指导。

wfveoks0

wfveoks01#

import { BrowserRouter as Router, Route } from 'react-router-dom';    
import NotebookList from './NotebookList';    
import Notebook from './Notebook';    
import Note from './Note';    

const App = () => {
  return (
    <Router>
      <Route exact path="/" component={NotebookList} />
      <Route path="/notebooks">
          <Route path="notebook/:notebookId" component={Notebook} />
          <Route path="notebook/:notebookId/note/:noteId" component={Note} />
      </Route>
    </Router>
  );
};

export default App;
9bfwbjaz

9bfwbjaz2#

Router组件***包含***呈现所有与当前URL路径匹配的内容。如果希望组件单独呈现,则将路由呈现到Switch组件中。请记住,在Switch中,路径顺序和特定性很重要。按照路径特异性的相反顺序对路由进行排序,例如 * 更多 * 特定路径在 * 更少 * 特定路径之前。这消除了在几乎100%的用例中使用exact属性的需要。
示例:

import { BrowserRouter as Router, Switch } from 'react-router-dom';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/notebook/:notebookId/note/:noteId" component={Note} />
        <Route path="/notebook/:notebookId" component={Notebook} />
        <Route path="/" component={NotebookList} />
      </Switch>
    </Router>
  );
};

相关问题