【问题标题】:Dynamically create React Routes Using Data From Component State使用来自组件状态的数据动态创建 React 路由
【发布时间】:2021-09-14 00:27:16
【问题描述】:

我正在尝试使用 react-router-dom 动态创建路由。路线将取决于我在其中一个组件中拥有的状态的 ID。我怎样才能做到这一点? App.js:

function App() {
  return (
    <div className="App">
      <Router>
        <Route path="/" component={Categories}></Route>
        <Route path="/:cat" component={Recipes}></Route>
      </Router>
    </div>
  );
}

我想从中获取 id (:cat) 的Categories.js - 状态类别有一个 id 值:

class Categories extends React.Component {
    state = {
        categories: []
    }

    componentDidMount() {
        fetch('http://localhost:8000/api/categories/')
            .then(response => response.json())
            .then(data => {
                this.setState({categories: data});
            });
    }

    render() {
        return (
            
        );
    }
}

我见过其他人使用 useParams,但我不能这样做,因为 Categories 是一个类。 谢谢你的帮助。

【问题讨论】:

  • &lt;Route path="/:cat" component={Recipes} /&gt; 是创建动态路由所需的全部内容。您是否真的想问一个不同的问题,例如如何导航到动态路线?没错,useParams 钩子不能在类组件中使用,但它也不用于生成路由,它为您提供当前匹配的路由 match.params。请说明您要做什么以及有什么问题(如果有的话)。
  • 所以'categories'状态有一个'id'属性。我想要做的是使用类别中的 id 创建多个路由。例如/类别 = [id=4]。我希望路线是“/ 4”。如果 categories=[id=8],路由应该是“/8”。
  • path="/:cat" 处理这个问题。 “:cat”是路径实际值的“占位符”,即如果您导航到“/4”,那么在路由中match.params.cat 将是"4"。这有意义吗?此外,categories = [id=4] 不是有效的数组语法。

标签: reactjs react-hooks react-router


【解决方案1】:

使用

this.props.match.params

即:

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

function App() {
  return (
    <div className="App">
      <p>R</p>
      <BrowserRouter>
       <Switch>
        <Route path="/categories/:id" component={Recipes}></Route>
        <Route path="/" component={Categories}></Route>
       </Switch>
      </BrowserRouter>
    </div>
  );
}

class Categories extends React.Component {
  state = {
    categories: []
  };

  componentDidMount() {
    fetch('http://localhost:8000/api/categories/')
        .then(response => response.json())
        .then(data => {
            this.setState({categories: data});
        });
}
  render() {
    return (
      <div>
        {this.state.categories.map((c) => (
          <div>CAT: {c.name}</div>
        ))}
      </div>
    );
  }
}

class Recipes extends React.Component {
  state = {};

  componentDidMount() {
     console.log('Params:',this.props.match.params)
  }

  render() {
    return <div></div>;
  }
}
export default App;

【讨论】:

  • 非常感谢,现在更有意义了。
猜你喜欢
  • 2019-06-09
  • 2017-06-17
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 2021-04-09
  • 2020-04-07
相关资源
最近更新 更多