【发布时间】:2019-05-19 21:42:31
【问题描述】:
我对 ReactJS 比较陌生。
我在更新组件状态时遇到问题。 当我控制台记录我的 api 获取的结果时,该对象在那里并且没有未定义。
这是我正在使用的代码:
class Article extends Component {
state = { post: {} };
componentDidMount() {
const id = this.props.match.params.id;
fetch(`/posts/${id}/`)
.then(res => res.json())
.then(post => {
this.setState(post);
console.log(post);
});
}
renderContent() {
if (
Object.entries(this.state.post).length === 0 &&
this.state.post.constructor === Object
) {
return <p>Blog does not exist sadly</p>;
} else {
return (
<div>
{" "}
{Object.keys(this.state.post).map(p => (
<div
style={{ maxWidth: "auto", textAlign: "centre" }}
key={this.state.post[p].title}
>
<Header heading={this.state.post[p].title} />
<div
style={{ padding: "40px" }}
dangerouslySetInnerHTML={{ __html: this.state.post[p].content }}
/>
</div>
))}
</div>
);
}
}
render() {
return (
<div>
{this.renderContent()}
<Footer />
</div>
);
}
}
export default Article;
这是一个 api 获取的结果:
{"_id":"5ce1ae8fc915dc48d13d7c1c","title":"example title","content":"example content"}
返回 MongoDB 查询结果的表达代码:
router.get("/posts/:id", function(req, res, next) {
MongoClient.connect("mongodb://localhost:27017/express", function(
err,
client
) {
if (err) throw err;
var db = client.db("express");
var id = parseInt(req.params["id"]);
db.collection("posts")
.find()
.sort({ _id: 1 })
.toArray(function(err, result) {
if (err) throw err;
if (result.length > 0) {
res.send(result[id]);
} else {
res.status(403);
}
});
});
});
这似乎只在使用单个结果获取时发生,而不是在我获取对象数组时发生。
更新:
尝试调用 console.log(this.state) 而不是调用 console.log(this.state.post 并将其取回:
{post: {}, _id: "5ce1ae8fc915dc48d13d7c1c", title: "example title", content: "example content"}
好像它在那里,但我更新状态错误?
【问题讨论】:
-
你能把你的代码贴在codesandbox或stack blitz上吗?或提供更多信息,很难从这些信息中分辨出来。
-
嗨,我添加了更多代码。抱歉,从未使用过代码沙箱或堆栈闪电战。很快就会调查。
-
在 renderContent 函数中使用 map 函数来处理数组。相反,您可以直接访问您的一篇帖子。
-
当我控制台记录 this.state.post 时,我得到一个空对象 {}。所以没有什么可以渲染的。
-
我尝试调用 console.log(this.state) 而不是调用 console.log(this.state.post) 并将其取回 {post: {}, _id: "5ce1ae8fc915dc48d13d7c1c", title: "example title", content: "example content"}... 好像就在那里,但里面有一个空对象???
标签: reactjs mongodb express nodes