如何将 Match 对象包含到 ReactJs 组件类中?

IT技术 reactjs react-router
2021-05-25 23:36:45

我试图通过将 Match 对象传递到我的react组件类来使用我的 url 作为参数。但是它不起作用!我在这里做错了什么?

当我将组件创建为 JavaScript 函数时,一切正常,但是当我尝试将组件创建为 JavaScript 类时,它不起作用。

也许我做错了什么?如何将 Match 对象传递给我的类组件,然后使用它来设置我的组件的状态?

我的代码:

import React, { Component } from 'react';

import axios from 'axios';

import PropTypes from 'prop-types';

class InstructorProfile extends Component {  

  constructor(props, {match}) {

    super(props, {match});

    this.state = {
        instructors: [],
        instructorID : match.params.instructorID
    };

  }

   componentDidMount(){


      axios.get(`/instructors`)
      .then(response => {
        this.setState({
          instructors: response.data
        });
      })
      .catch(error => {
        console.log('Error fetching and parsing data', error);
      });
    }

  render(){
    return (
      <div className="instructor-grid">

        <div className="instructor-wrapper">

       hi

        </div>

      </div>
    );
  }
}

export default InstructorProfile;
4个回答

React-Router 的Route组件match默认通过 props对象传递给它包装的组件。尝试用constructor以下方法替换您的方法:

constructor(props) {
    super(props);
    this.state = {
        instructors: [],
        instructorID : props.match.params.instructorID
    };
}

希望这可以帮助。

你的构造函数只接收 props 对象,你必须把match放进去......

constructor(props) {
  super(props);
  let match = props.match;//← here

  this.state = {
    instructors: [],
    instructorID : match.params.instructorID
  };
}

然后你必须通过 props int 传递匹配对象到父组件:

// in parent component...
render(){
  let match = ...;//however you get your match object upper in the hierarchy
  return <InstructorProfile match={match} /*and any other thing you need to pass it*/ />;
}

对我来说,这不是包装组件:

export default (withRouter(InstructorProfile))

你需要导入withRouter

import { withRouter } from 'react-router';

然后你可以通过 props 访问匹配参数:

  someFunc = () => {
      const { match, someOtherFunc } = this.props;
      const { params } = match;
      someOtherFunc(params.paramName1, params.paramName2);
  };

在组件类中使用匹配

如react-router文档中所述。在组件类中使用 this.props.match。在常规函数中使用 ({match})。

用例:

import React, {Component} from 'react';
import {Link, Route} from 'react-router-dom';
import DogsComponent from "./DogsComponent";

export default class Pets extends Component{
  render(){
    return (
      <div>
        <Link to={this.props.match.url+"/dogs"}>Dogs</Link>
        <Route path={this.props.match.path+"/dogs"} component={DogsComponent} />
      </div>
        
    )
      
  }
}

或使用渲染

<Route path={this.props.match.path+"/dogs"} render={()=>{
  <p>You just clicked dog</p>
}} />

经过几天的研究,它对我有用。希望这可以帮助。