【问题标题】:Unable to console.log props using Link无法使用 Link 控制台记录道具
【发布时间】:2020-04-13 07:07:25
【问题描述】:

我正在尝试制作单个 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;

【问题讨论】:

    标签: javascript reactjs react-native react-redux react-router


    【解决方案1】:

    我刚刚运行了您的代码,看起来问题出在使用/:post-id。我将其更改为 /:pid 并且有效。当我控制台日志this.props.match

    时,我得到了以下对象
    {
      "path":"/:pid",
      "url":"/1",
      "isExact":true,
      "params":
        {
          "pid":"1"
        }
      }
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      你必须用路由器加载组件

      试试这个

      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多