【问题标题】:React-router-dom params undefined in nested route after using link使用链接后,在嵌套路由中未定义 React-router-dom 参数
【发布时间】:2022-01-21 18:19:25
【问题描述】:

我需要一个开关组件来访问路由参数。开关呈现在其中一个路由中,但也呈现在其外部。有没有办法在路由之外渲染的组件中获得相同的参数?提前感谢您的帮助!

【问题讨论】:

标签: react-router


【解决方案1】:

不直接通过路由传递参数并通过视图组件保持简单通常是一种很好的模式。您可以使用useContext,然后使用组件中的useContext 挂钩让每个组件(路由)插入该状态。

例如...

app.js

import { useState } from 'react';
import { BrowserRouter as Router } from 'react-router-dom';
import { Routes } from "./auth/routes.js";
import { GlobalContext } from './globals/GlobalContext.js';

const App = () => {
  // variables
  const [someState, setSomeState] = useState('hello world');

  // render
  return (
    <div>
      <GlobalContext.Provider value={{someState, setSomeState}}>
        <Router children={Routes} basename={process.env.REACT_APP_PUBLIC_URL} />
      </GlobalContext.Provider>
    </div>
  );
}

GlobalContext.js

import { createContext } from 'react';

export const GlobalContext = createContext("");

routes.js


import { Route, Switch } from "react-router-dom";

// views
import ViewOne from '../views/ViewOne.js';
import ViewTwo from '../views/ViewTwo.js';

// globals
import { frontendLinks } from '../globals/index.js';

export const Routes = (
  <Switch>
    <Route exact path={frontendLinks.viewOne} component={ViewOne}></Route>
    <Route exact path={frontendLinks.viewTwo} component={ViewTwo}></Route>
  </Switch>
);

现在是视图...

import { useContext } from 'react';

// globals
import { GlobalContext } from '../globals/GlobalContext.js';

const ViewOne = () => {
  const { someState } = useContext(GlobalContext);

  return (
    <div>
      <h1>{someState}<h1>
    </div>
  )
}

export default ViewOne;

import { useContext } from 'react';

// globals
import { GlobalContext } from '../globals/GlobalContext.js';

const ViewTwo = () => {
  const { someState } = useContext(GlobalContext);

  return (
    <div>
      <h1>{someState}<h1>
    </div>
  )
}

export default ViewTwo;

如果您不想在 app.js 文件中管理共享状态,我建议您观看此视频以管理不同文件中的 useContext 状态 > https://www.youtube.com/watch?v=52W__dKdNnU

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 2018-06-26
    • 2022-12-22
    • 2020-10-10
    • 2020-11-06
    • 1970-01-01
    • 2022-01-13
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多