Возникли проблемы при обновлении состояния компонента в ReactJS - PullRequest
1 голос
/ 20 мая 2019

Я относительно новичок в 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"}

, поэтому кажется, что он есть, но я обновляю состояниенеправильно?

Ответы [ 2 ]

1 голос
/ 20 мая 2019

Можете ли вы еще раз проверить, используете ли вы правильную функцию для установки состояния?

Это должно быть this.setState({ post }), а не this.setState(post)

class Article extends Component {
  state = { post: null };

  componentDidMount() {
    const id = this.props.match.params.id;
    fetch(`/posts/${id}/`)
      .then(res => res.json())
      .then(post => {
        this.setState({ post }, console.log(this.state.post));
      });
  }

  renderContent() {
    const { post } = this.state
    if (!post) {
      return <p>Blog does not exist sadly</p>;
    } else {
      return (
        <div>
          {" "}
          <div
              style={{ maxWidth: "auto", textAlign: "centre" }}
              key={post.title}
            >
              <Header heading={post.title} />
              <div
                style={{ padding: "40px" }}
                dangerouslySetInnerHTML={{ __html: post.content }}
              />
            </div>
        </div>
      );
    }
  }

  render() {
    return (
      <div>
        {this.renderContent()}
        <Footer />
      </div>
    );
  }
}

export default Article;
0 голосов
/ 20 мая 2019

Как уже упоминалось в моем комментарии, ваша функция renderContent ожидает массив.Вы можете заключить свой единственный результат в массив или получить прямой доступ к объекту, не используя функцию map () для решения вашей проблемы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...