Я относительно новичок в ReactJS.
У меня проблемы с обновлением состояния компонентов.Когда я консоль записываю в журнал результаты моего api fetch, объект находится там и не является неопределенным.
Это код, с которым я работаю:
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);
}
});
});
});
Кажется, что это происходит только при работе с одной выборкой результатов, а не при выборке массива объектов.
update:
попытался вызвать console.log (this.state) вместо вызова console.log (this.state.post и получить его обратно:
{post: {}, _id: "5ce1ae8fc915dc48d13d7c1c", title: "example title", content: "example content"}
, поэтому кажется, что он есть, но я обновляю состояниенеправильно?