【问题标题】:How to get params from route in REACTJS如何从 REACTJS 中的路由获取参数
【发布时间】:2019-09-22 16:13:07
【问题描述】:

我想在我的反应类中获取参数

我有文件index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import { App, addPost, Child } from './components/App';
import { Switch , Route, BrowserRouter } from 'react-router-dom'

ReactDOM.render((
   <BrowserRouter>
    <Switch>
        <Route exact path="/" component={App} />
        <Route path="/dodajpost" component={addPost} />
        <Route exact path="/:id" component={App}  /> // this one
    </Switch>
  </BrowserRouter>
), document.getElementById('root'));

现在在我的课堂上,我想获取参数 ":id" 并将其发送到服务器,但我不知道如何获取它

export default class Post extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: true,

     };
}
componentDidMount () {
    const { handle } = this.props.match.params
    console.log(handle) // undefined
  }

如何从路由中获取componentDidMount 的参数?

我尝试了很多东西,但都没有成功

【问题讨论】:

标签: reactjs


【解决方案1】:

因为您的Route 的参数名称为id

<Route exact path="/:id" component={App}  />

取而代之的是,

const { handle } = this.props.match.params

你应该这样做,

const { id } = this.props.match.params

console.log(id)

注意:您有 2 个Route's 用于 App 组件。因此,当您已经在 App 组件中并尝试导航到 path="/:id" 时,您将不会获得 id 值,因为您可能需要 componentDidUpdate 方法。

componentDidUpdate () {
  const { id } = this.props.match.params
  console.log(id)
}

或者你可能在这里打错了&lt;Route exact path="/:id" component={App} /&gt;,而不是App作为组件你可能有Child(帖子)组件&lt;Route exact path="/:id" component={Child} /&gt;

Demo

【讨论】:

    猜你喜欢
    • 2020-01-02
    • 2018-06-25
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    相关资源
    最近更新 更多