6

在这里,我将返回当前的 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 包装每个组件,然后将密钥硬编码到不同的消息,但这似乎没有必要。

4

2 回答 2

2

您可以使用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> }
  </>);
}
于 2020-03-03T09:25:26.980 回答
2

您正在将 browserHistory 传递给路由器。为什么不将相同的内容传递给 Snackbar 组件?历史对象中会有 url 和 location,这些可以在 Snackbar 中使用,并根据需要呈现消息。例如:

应用程序

import React from "react";

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

小吃店

const SnackBar = ({history, ...props}) => {
// const message = `Current location is ${history.location.url}`;
// Format and use the message as needed
 return (
  <>
   <CP.Snackbar
        {...props}
    />
  </>
 );
}

PS:如果要访问 的任何子组件内的位置Router,我建议使用useLocation钩子。但是在这种情况下,Snackbar它是兄弟,并且 react-router 上下文不会设置为使用路由器挂钩。

于 2020-03-03T10:42:20.223 回答