我有一个关于 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 作为组件的参数(在本例中为 QuestionLink)
- 从 REST API 中检索问题,作为 ComponentDidMount 中特定资源(带有 ID)的获取
- 安装 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 。如果我广泛进行这种处理和/或需要只有服务器拥有的信息,我可能只会这样做。
关于javascript - 如何在React中通过Id获取特定问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55819087/