反应路由器(react-router-dom)从当前路由(功能组件)设置页面标题?

ben*_*hky 4 page-title reactjs react-router react-router-dom

我认为这很容易,但仍然找不到简单的解决方案。我只想将页面标题(和 document.title)设置为我选择的指定字符串。我知道我可以访问 useLocation 并获取当前路线,但这不适用于逻辑人类命名。例如,我的路线可能是 /new,但我希望页面标题为“添加新内容”。请注意,我为页面标题添加了一个新的道具,这似乎是添加它的合乎逻辑的位置(然后使用 useEffect 来拉动它),但无法弄清楚如何访问此道具。

如果这不是正确的方法,你会怎么做?我应该为当前 url(useLocation) 设置字典/查找并分配人工页面标题吗?

主要目标:如果有人直接点击 URL“/new”,您将如何设置标题?

我当前的结构来自基础创建反应应用程序。

在我的index.js中

ReactDOM.render(
    <React.StrictMode>
      <Router>
        <App />
      </Router>
    </React.StrictMode>,
    document.getElementById('root')
);
Run Code Online (Sandbox Code Playgroud)

应用程序.js

<div className="quiz-app-row">
        <SideBarNav />
        <div className='quiz-app-col'>
          <h1>{TITLE HEREEEEE}</h1>
          <Switch>
            <Route exact component={Home} path="/" title='home' />
            <Route exact component={Example} path="/manage" title='example' />
            <Route exact component={CreateQuiz} path="/new" title='New Quiz' />
          </Switch>
        </div>
      </div>
Run Code Online (Sandbox Code Playgroud)

ben*_*hky 5

感谢所有人的回复,但我觉得他们中的大多数似乎对于我想要完成的事情来说太过分了,并且不需要额外的包。相反,我只是创建了一个查找集合并以这种方式分配了标题。我总共只有 ~7 个链接,所以这似乎是可以管理的。

const [pageTitle, setPageTitle] = useState('Home');

  const titleMap = [
    {path: '/', title:'Home'},
    {path: '/manage', title:'Manage'},
    {path: '/new', title:'New Quiz'}
  ]

  let curLoc = useLocation();
  useEffect(() => {
    const curTitle = titleMap.find(item => item.path === curLoc.pathname)
    if(curTitle && curTitle.title){
      setPageTitle(curTitle.title)
      document.title = curTitle.title
    }
  }, [curLoc])
Run Code Online (Sandbox Code Playgroud)