簡體   English   中英

無法使用 Link 控制台記錄道具

[英]Unable to console.log props using Link

我正在嘗試制作一個 web 應用程序。 基本上,我正在嘗試使用 ReactRouter 來顯示作為路由參數傳遞的內容。 但是,我無法做到這一點。 為了檢查是否有問題,我決定 console.log out this.props.match,仍然沒有任何顯示。 有人可以解釋問題是什么嗎? 和一個可能的解決方法?

我的代碼是-

import React from 'react';

export default class Post extends React.Component {


    state = {
        id: null
    }

    componentDidMount(props) {
        console.log(this.props.match);
    }

    render = () => {
        return (<div>Hello WOrld</div>)
    }
}

App.js 文件:

import React, { Fragment, Component } from 'react';
import Navbar from './components/Navbar';
import Home from './components/Home';
import Contact from './components/Contact';
import About from './components/About'
import Post from './components/Post';
import { BrowserRouter, Route } from 'react-router-dom';



class App extends Component {
  render = () => {
    return (

      <BrowserRouter>
        <div className="App">
          <Navbar />
          <Route exact path="/" component={Home} />
          <Route path="/contact" component={Contact} />
          <Route path="/about" component={About} />
          <Route path="/:post-id" component = {Post} />
        </div>
      </BrowserRouter>

    );
  }
}

export default App;

我剛剛運行了您的代碼,看起來問題出在使用/:post-id 我將其更改為/:pid並且它起作用了。 當我控制台記錄 this.props.match 時,我得到了以下this.props.match

{
  "path":"/:pid",
  "url":"/1",
  "isExact":true,
  "params":
    {
      "pid":"1"
    }
  }

我希望這有幫助。

您必須使用路由器加載組件

嘗試這個

import { withRouter } from 'react-router-dom';

class Post extends React.Component {


    state = {
        id: null
    }

    componentDidMount(props) {
        console.log(this.props.match);
    }

    render = () => {
        return (<div>Hello WOrld</div>)
    }
}

export default withRouter(Post);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM