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

问题描述 投票:4回答:3

我试图通过将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;
reactjs react-router
3个回答
9
投票

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

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

希望这可以帮助。


1
投票

你的构造函数只接收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*/ />;
}

0
投票

在组件类中使用匹配

如反应路由器文档中所述。在组件类中使用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>
}} />

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

© www.soinside.com 2019 - 2024. All rights reserved.