【问题标题】:componentDidMount not firing in ReactcomponentDidMount 没有在 React 中触发
【发布时间】:2018-09-19 05:39:22
【问题描述】:
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';

import Post from './components/Post.jsx';
import Feed from './components/Feed.jsx';

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      view: 'feed',
      collection: ''
    }
  }


  componentDidMount() {
    console.log('component did mount')
    this.getCollection();
  }

  async getCollection() {
    try {
      const response = await fetch('/api/page');
      const responseJSON = await response.json();

      this.setState({ collection: responseJSON }, () => {
        console.log("App Component - getCollection() State Updated", this.state);
      });

    } catch (error) {
      console.log("App Component - getCollection() error", error);
    }
  }


  render() {
    return (
      <div>
       Text
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

无法让组件挂载到功能。尝试向我的 mongodb 发出 ajax 请求并在客户端呈现该请求。我现在需要做的就是进行状态更改,将集合设置为我返回的信息。我尝试使用 Ajax 请求,但没有奏效。现在我正在根据另一位贡献者的建议实现异步获取调用。

非工作 ajax 请求:

截至目前,componentDidMount仍未被触发,状态的collection属性仍为空字符串。

【问题讨论】:

  • 你必须绑定getCollection
  • 我绑定了成功和错误的情况,我还需要在哪里?我无法触发成功控制台日志案例
  • 你需要添加一个render函数
  • 你能把整个文件的代码加进去吗?

标签: reactjs


【解决方案1】:

我建议使用 Fetch API 进行 AJAX 调用并使用 ES6 Async/Await,因为仅为 Ajax 导入整个库似乎有点过头了。

import React from 'react';
import ReactDOM from 'react-dom';


class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      collection: ''
    }
    this.getCollection = this.getCollection.bind(this)
  }


  componentDidMount() {
    console.log('component did mount')
    this.getCollection();
  }

  async getCollection() {
    try {
      const response = await fetch('/api/blogs');
      const responseJSON = await response.json();

      this.setState({ collection: responseJSON }, () => {
        console.log("App Component - getCollection() State Updated", this.state);
      });

    } catch (error) {
      console.log("App Component - getCollection() error", error);
    }
  }

    render() {
      return (
         <div>
            <h1>Welcome</h1>
          </div>
      );
    }
  }

  ReactDOM.render(<App /> , document.getElementById('app'));

我不确定你在用你的渲染做什么,但我把它省略了。希望这将阐明如何最好地执行您想要的操作。

【讨论】:

  • 我尝试实现异步 getCollection 但我收到此错误:未捕获错误:模块构建失败:SyntaxError:意外令牌,预期; (72:15)
  • 您能否在您的问题中链接整个文件。
  • 感谢您的帮助并已实现您的代码,componentDidMount 仍未触发
  • 你是如何使用这个组件的?使用您所做的更改更新问题。所以我可以完全看到你是如何使用它的。因为它对我有用。
【解决方案2】:

要让componentDidMount 触发,您需要render 函数。因为组件先渲染,然后调用函数componentDidMount。

我认为将此添加到您的课程应该可以解决您的问题。

render() {
  return null;
}

【讨论】:

  • 我有一个渲染返回语句。我没有包括它,因为我认为问题不在于那里。我认为这与绑定有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多