如何在React中通过ID获取特定问题

时间:2019-04-23 20:39:51

标签: javascript reactjs

我有一个关于Mern堆栈的问题。我有一个类似于stackOverflow的程序,您在其中发布问题,有人可以答复。目前,我的程序可以发布问题,还可以获取所有问题的列表。我在每个问题上都有一个链接,因此,当您单击任何一个问题时,都应打开该特定问题。问题的ID在溃败中可见,例如http://localhost:3000/link/5cae2dda9723ad157c085370。问题在于获取特定问题的内容

//*this code is able get the list of all questions*//

import React, { Component } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import { EMLINK } from "constants";

const Question = props => (
  <tr>
    <td>{props.question.author_name}</td>
    <td>{props.question.question_title}</td>
    <td>{props.question.question_input}</td>
    <td>
      <Link to={"/link/" + props.question._id}>comment</Link>

    </td>
  </tr>
);

class QuestionList extends Component {
  constructor(props) {
    super(props);
    this.state = { questions: [] };
  }

  componentDidMount() {
    axios
      .get("http://localhost:4000/questions/")
      .then(response => {
        this.setState({ questions: response.data });
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  questionList() {
    return this.state.questions.map(function(currentQuestion, i) {
      return <Question question={currentQuestion} key={i} />;
    });
  }

  render() {
    return (
      <div>
        <h3>Question List</h3>
        <table className="table table-striped" style={{ marginTop: 20 }}>
          <thead>
            <tr>
              <th>Name</th>
              <th>Title</th>
              <th>Question</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>{this.questionList()}</tbody>
        </table>
      </div>
    );
  }
}
export default QuestionList;
*/The below code is the one that i need to only show one specific question by ID*//

import React, { Component } from "react";
import { Link } from "react-router-dom";

import axios from "axios";
const Questioners = props => (
  <tr>
    <td>{props.question.author_name}</td>
    <td>{props.question.question_title}</td>
    <td>{props.question.question_input}</td>
  </tr>
);
class QuestionLink extends Component {
  constructor(props) {
    super(props);

    this.state = {
      author_name: "",
      question_title: "",
      question_input: ""

    };
  }

  render() {
    return (
      <div>
        <h3>Question List</h3>
        <table className="table table-striped" style={{ marginTop: 20 }}>
          <thead>
            <tr>
              <th>Name</th>
              <th>Title</th>
              <th>Question</th>
            </tr>
          </thead>
          <tbody>{}</tbody>
        </table>
      </div>
    );
  }
}

export default QuestionLink;

2 个答案:

答案 0 :(得分:1)

在这些情况下,我已完成以下操作:

  1. 将ID作为组件的参数(在本例中为QuestionLink)
  2. 从REST API中检索问题,作为ComponentDidMount中特定资源(具有ID)的获取
  3. 在安装您的react应用(顶级组件)时,请从URL中检索ID。我更喜欢使用查询字符串

import { parse } from "querystring";
let values = parse(window.location.search.substring(1));

然后挂载<QuestionLink questionId={values["questionId"]} />

编辑:我尚未为此使用模板引擎,但是它应该非常适合此类工作。您可以使用pug之类的东西进行服务器端渲染,使用pass the id to the view来自中间件,以及render to a react component。如果我进行了广泛的此类处理和/或仅需要服务器拥有的信息,我可能只会这样做。

答案 1 :(得分:0)

感谢您的帮助,我成功了。我按照以下方式解决了问题

<Route
              path="/link/:id"
              render={props => <QuestionLink {...props} />}
            />
 this.state = {
      currentQuestion: {}
    };
componentDidMount() {
    axios
      .get("http://localhost:4000/questions/")
      .then(response => {
        this.setState({
          currentQuestion: response.data.find(elm =>
            elm._id == this.props.match.params.id
          )
        });
      })