reactjs - 如何根据当前 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 包装每个组件,然后将密钥硬编码到不同的消息,但这似乎没有必要。
解决方案
您可以使用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> }
</>);
}
推荐阅读
- python - 如何用 Numpy 数组替换 For 循环和 IF 语句
- javascript - 如何下载 html 页面,包括 JS 所做的更改
- angular6 - 如何使用 Angular 6 + Handsontable 根据另一个单元格值仅更改一个单元格值?
- vue.js - 可以为 Vuex 模块、突变和动作使用 ES6 类吗?
- c# - 为什么 CompareTo 不使用 ASCII 代码排序对我的字符串进行排序?
- responsive-design - Bootstrap Shopify 导航不会崩溃
- sql-server - 实现 TSQL 函数“自定义值集中的值”的最有效方法
- python - tensorflow.python.framework.errors_impl.InvalidArgumentError:您必须为占位符张量“sequential_input”提供一个值
- sql - 对每个 id 的每一行计数一次并获取计数 SQL Select 查询
- typescript - 类型“未定义”不可分配给类型