首页 > 解决方案 > 如何根据当前 url / url 片段呈现不同的消息

问题描述

在这里,我将返回当前的 react dom 内容:

  return (
    <React.Fragment>
      {inProduction ? null : <CP.Dev/>}
      <CP.Snackbar
        {...p as any}
      />
      <Router history={browserHistory}>
        <Switch>
          <Route path="/login" component={Login} />
          <Route path="/signup" component={Signup} />
           {authRoutes}
        </Switch>
      </Router>
    </React.Fragment>
  );

所以.. Snackbar 组件为每条路线呈现 - 目标:我想要做的是根据 url 呈现不同的欢迎消息 - 最好的方法是什么?如何侦听 url 更改,然后根据 url 呈现不同的消息?

或者,我可以用 Snackbar 包装每个组件,然后将密钥硬编码到不同的消息,但这似乎没有必要。

标签: reactjsreact-routerreact-fragment

解决方案


您可以使用react-router-dom history来了解 URL 中的更改。这是一个例子:

import React from "react";
import { useHistory } from "react-router-dom";

const App = () => {
  const history = useHistory();

  return (<>
     { history.location.pathname === "/" ? <div>Home</div> : <div>Other Component</div> }
  </>);
}

推荐阅读