首页 > 解决方案 > 无法从 Link 接收道具

问题描述

我正在学习反应,并试图通过 Link 将道具(命名为 classId)传递给另一个组件(ClassPage.js),但是我无法接收道具并且它返回未定义。感谢您的时间,感谢。

App.js - 我想在我的 ClassPage 组件中访问 c​​lassId(来自 ClassList 中的链接)

<Route path="/classpage/:classId" exact render={() => <ClassPage isLoggedIn={this.state.isLoggedIn} user={this.state.user}/>} />

ClassList.js - 尝试通过 Link 将数据传递给 ClassPage 组件

import React, { Component } from "react";
import { Link } from "react-router-dom";
import "./ClassList.css";

class ClassList extends Component {

render() {

console.log(this.props.classId); //recived
console.log(this.props.classTitle); //recived
console.log(this.props.classDescription); //recived
console.log("click link and direct to Class Page");


// Problem located in here, try to pass data to ClassPage.js
return (
    <div>
    <Link to={"/classpage/"+this.props.classId}> 

      <h3 className="titleStyle">{this.props.classTitle}</h3> 

    </Link>
        <div className="row">
      <div className="col-sm-6 text-secondary">
        Instructor: {this.props.instructor}
      </div>
      <div className="col-sm-6 text-secondary">
        Meeting day: {this.props.meetingDay}
      </div>
    </div>
    </div>
);
}
}

export default ClassList;

ClassPage.js - 无法从 ClassList 组件接收 classId

import React from 'react';
import Navbar from "../Components/Navbar.js";
import Footer from "../Components/Footer.js";
import PostTable from "../Components/PostTable.js";


class ClassPage extends React.Component {
  constructor(props) {
    super(props);

    console.log("class ID");
    console.log(this.props.classId); //Problem located in here
    //cannot receive - this.props.classId

    this.state  = {
      classPostsData: []
    };
  }

componentDidMount() {
    fetch("https://api.myjson.com/bins/jfuqc") 
    // fetch from localhost by this.props.classId
        .then(data => data.json())
        .then(data => this.setState({classPostsData: data}))
  }

render() {
    return(
      <div>
        <Navbar isLoggedIn={this.props.isLoggedIn} />

        <h1>{this.props.classTitle}</h1> 
        <p>{this.props.classDescription}</p>
        {this.state.classPostsData.map(post => {
          return (
            <PostTable
              key={post.post_ID}
              post_ID={post.post_ID}
              post_Title={post.post_Title}
              post_note={post.post_note}
            />
          );
        })}
        <Footer isLoggedIn={this.props.isLoggedIn} />
      </div>
    );
  }
}

export default ClassPage;

更新:

类列表.js

const toClassPage = {
   pathname: "/classpage/" + this.props.classId,
   state: {
            classId: this.props.classId,
            classTitle: this.props.classTitle,
            classDescription: this.props.classDescription 
          }
}

<Link to={toClassPage}>
      <h3 className="titleStyle">{this.props.classTitle}</h3> 
</Link>

ClassPage.js

constructor(props) {
    super(props);

    console.log("class ID/Title/Description");
    console.log(this.props.location.state.classId);
    console.log(this.props.location.state.classTitle);
    console.log(this.props.location.state.classDescription);

    this.state  = {
        classPostsData: []
    };
}

来自 Chrome 的错误:

TypeError: Cannot read property 'state' of undefined
new ClassPage
src/Pages/ClassPage.js:13

   10 | super(props);
   11 | 
   12 | console.log("class ID/Title/Description");
 > 13 | console.log(this.props.location.state.classId);
      | ^  14 | console.log(this.props.location.state.classTitle);
   15 | console.log(this.props.location.state.classDescription);
   16 | 

标签: reactjsroutesreact-props

解决方案


您不需要根据您的路线访问类 ID。你可以把它从href中撕下来。

let id = window.location.href.split("/")[window.location.href.split("/").length -1];

如果您只需要地址栏中的该 ID,则上面的代码应该可以解决问题。

如果您需要的不仅仅是类 id,您还可以通过链接将道具传递给状态。

   <Link to={{
      pathname: `/classpage/${this.props.classId}`,
      state: {
        classId: this.props.classId,
        title: this.props.classTitle,
        description: this.props.classDescription 
      }
    }}>
<h3 className="titleStyle">{this.props.classTitle}</h3> 
</Link>

然后,您将通过 this.props.location.state 访问它


推荐阅读