【问题标题】:Having trouble updating component state in ReactJS在 ReactJS 中更新组件状态时遇到问题
【发布时间】: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


【解决方案1】:

您能否再次检查您是否使用了正确的函数来设置状态?

应该是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;

【讨论】:

  • 您好,好像没有影响。我将我的 git repo 重置回以前的版本,在该版本中我做了一些稍微不同的事情......当 api 返回 [{"_id":"5ce1ae8fc915dc48d13d7c1c","title":"example title","content": “示例内容”}] 而不是上面的结果。唯一的区别是方括号。
  • 您当前设置状态的方式将导致您从 api 获得的 post 对象被插入到没有密钥的状态中,即您将拥有 this.state = { post: { your fetched post obj } } 而不是 this.state = { your fetched post obj }
【解决方案2】:

正如我在评论中提到的,您的 renderContent 函数需要一个数组。您可以将单个结果包装到数组中或直接访问对象,而无需使用 map() 函数来解决您的问题。

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2023-02-05
    • 1970-01-01
    • 2021-04-23
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多