【问题标题】:How to include the Match object into a ReactJs component class?如何将 Match 对象包含到 ReactJs 组件类中?
【发布时间】:2021-05-08 13:14:32
【问题描述】:

我试图通过将 Match 对象传递给我的反应组件类来使用我的 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


    【解决方案1】:

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

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

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 在构造函数中捕获参数是否合适 - 是否保证构造组件时match对象将存在?
      • 根本不保证,但问题表明他们确实从一开始就将匹配传递给组件。我不想让答案复杂化。
      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        在组件类中使用匹配

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

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

        【讨论】:

          【解决方案5】:

          在功能组件中,匹配作为 props 的一部分传入,如下所示:

          export default function MyFunc(props) {
          //some code for your component here...
          }
          

          在一个类组件中它已经被传入了;你只需要像这样引用它:

          `export default class YourClass extends Component {
               render() {
                  const {match} = this.props;
                  console.log(match);
                  ///other component code 
              }
          }`
          

          【讨论】:

            猜你喜欢
            • 2013-06-17
            • 2015-09-09
            • 2016-07-16
            • 2017-12-16
            • 1970-01-01
            • 2018-11-19
            • 1970-01-01
            • 1970-01-01
            • 2020-04-26
            相关资源
            最近更新 更多