【问题标题】:How to Get a specific question by Id in React如何在 React 中通过 ID 获取特定问题
【发布时间】:2019-04-25 16:13:08
【问题描述】:

我有一个关于 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;

【问题讨论】:

  • 动态ID将通过props.match.params.id...

标签: javascript reactjs


【解决方案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));

然后挂载&lt;QuestionLink questionId={values["questionId"]} /&gt;

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多