无法从网址获取ID

问题描述 投票:-1回答:3

您可以在这张图片上看到,我正在尝试从地址栏/网址获取ID。然后用户,单击该用户将被重定向到问题页面。从那里我无法获得ID。

enter image description here

在我的App.js文件中,有此组件,这将加载所有问题,我需要在下一页上存储ID,以便我可以通过ID在数组中搜索。

这是questions.js页面,多数民众赞成在渲染问题时使用。我需要网址中的ID

import React, { Component } from "react";
import QuestionItem from "./QuestionItem";
import Question from "./Question";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useParams
} from "react-router-dom";

export class Questions extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }

  render() {
    return this.props.dataFromParent
      .filter(e => e.id === 1) //Parse id from URL here, but HOW????
      .map((column, index) => (
        <div className="container mt-5" key={index}>
          {column.name}
          <br></br>
        </div>
      ));
  }
}

export default Questions;

这是我从app.jss出发的路线,我确实尝试将id解析为从路线到组件的道具。但这行不通。

<Questions
  exact
  path="/question/:id"
  dataFromParent={this.state.questions}
  idFromUrl={this.props.id}
  component={Questions}
></Question>

我是React的新手,所以我不知道该怎么做才能使它正常工作。

reactjs parameters react-router id
3个回答
0
投票

您可以通过执行以下操作来解析您的信息:

<Questions
  exact
  path={"/question:" + this.props.id }
  dataFromParent={this.state.questions}
  idFromUrl={this.props.id}
  component={Questions}
></Question>

并使用来自react-router的props.match.params和您的对象进行检索(一定要与Routerr一起导入)。要与withRouter一起使用,请先从react-router-dom导入它

import { withRouter } from "react-router-dom";

这是一个高阶组件,换句话说,它包装了您的组件,因此您可以在导出期间应用,如下所示:

export default withRouter(Questions);

此后,路由器将向您发送一个对象(我建议您执行console.log(this.props)以查看您的路径中withRouter提供的所有信息)

这里提供参考,祝您编程愉快!

https://reacttraining.com/react-router/core/api/withRouter


0
投票

您应该使用withRouter将路由器参数添加到Questions组件中,如下所示:

import React, { Component } from 'react';
import { withRouter }       from 'react-router-dom';

export class Questions extends Component {
    constructor(props) {
        super(props);

        this.state = {};
    }

    render() {
        const { match: { params } } = this.props;
        console.log(params); // here is your params object with id

        return this.props.dataFromParent
            .filter(e => e.id === 1) //Parse id from URL here, but HOW????
            .map((column, index) => (
                <div
                    className="container mt-5"
                    key={ index }
                >
                    { column.name }
                    <br></br>
                </div>
            ));
    }
}

export default withRouter(Questions);


0
投票

我找到了解决问题的方法。我无法想到要工作。但这现在有效!

enter image description here

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