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

编程入门 行业动态 更新时间:2024-10-27 20:28:23
本文介绍了如何将 Match 对象包含到 ReactJs 组件类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

我的代码:

import React, { Component } from 'react';从 'axios' 导入 axios;从 'prop-types' 导入 PropTypes;类 InstructorProfile 扩展组件 {构造函数(道具,{匹配}){超级(道具,{匹配});this.state = {导师:[],教员 ID : match.params.instructorID};}componentDidMount(){axios.get(`/instructors`).then(响应 => {this.setState({教师: response.data});}).catch(错误=> {console.log('获取和解析数据时出错', error);});}使成为(){返回 (<div className="instructor-grid"><div className="instructor-wrapper">你好

);}}导出默认的 InstructorProfile;

解决方案

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

constructor(props) {超级(道具);this.state = {导师:[],教员 ID : props.match.params.instructorID};}

希望这会有所帮助.

I am trying to use my url as a parameter by passing the Match object into my react component class. However it is not working! What am I doing wrong here?

When I create my component as a JavaScript function it all works fine, but when I try to create my component as a JavaScript class it doesn't work.

Perhaps I am doing something wrong? How do I pass the Match object in to my class component and then use that to set my component's state?

My code:

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;

解决方案

React-Router's Route component passes the match object to the component it wraps by default, via props. Try replacing your constructor method with the following:

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

Hope this helps.

更多推荐

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

本文发布于:2023-11-28 19:53:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643744.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   组件   类中   对象   Match

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!