反应componentDidMount没有开火

use*_*436 51 javascript reactjs

我设置了一个新的反应项目,由于某种原因,该componentDidMount方法没有被调用.

我已通过调用console.login 来验证此行为,componentDidMount但我无法在控制台中看到它的输出.

此外,this.setState()不起作用.

我很难过为什么componentDidMount不被召唤.我尝试使用React"v0.14.0"和"v0.14.3".

为什么'componentDidMount'没有被调用?

码:

var React = require('react');

var RecipePage = React.createClass({
  componentDidMount: function() {
    console.log('mounted!');
  },
  render: function() {
    return (
      <div>Random Page</div>
    );
  }
});

module.exports = RecipePage;
Run Code Online (Sandbox Code Playgroud)

P.B*_*key 39

当我componentWillMount()在同一个班级中定义了2x 时,这发生在我身上.这不会产生运行时错误.我只是删除了第二个定义,事情就开始了.

  • 快速解决!谢谢..这似乎是一个无心的错误。即使我最终在同一个类中添加了 2 个 componentDidMount ,导致第一个被覆盖..谢谢! (2认同)

use*_*436 24

所以...瞧瞧......我终于让它工作了(在一个后端专家的帮助下)."componentDidMount"方法未被触发的原因是因为我的服务器正在捆绑并提供服务器端的所有react + html内容.(只有"render"和"getInitialState"方法被调用才能创建通过客户端浏览器传递的"html"模板......但它停在那里因为它认为它已经完成了)

修复:找到一种方法通过服务器提供生成的"已编译"html,此外,允许反应自己的事件可以访问,并在客户端再次"触发".在编译我的"视图"文件(index.js或index.html)时,我包含了一个"Application.start()"脚本,它再次将我的bundle.js代码注入到模板中.然后在我的gulpfile中,导出"Application"变量,以便"view"文件可以访问它.

Gahh ......为此拉了我的头发.是时候阅读服务器端与客户端渲染了


use*_*949 9

就我而言,componentDidMount代码中还有另一个


Sig*_*gex 5

我有 create-react-app 模板。我将 ComponentDidMount 添加到 App 组件中。我在里面放了一个 console.log 和一个警报。它不会触发并且 React 或浏览器中没有错误。我在 chrome 和 firefox 中尝试过。

修复:对我有用的是重新启动我的电脑。然后它开始工作。我不知道为什么,但这可以解决问题。

更新:不是我有一个大写的 'C' 它是 'componentDidMount' 不是 'ComponentDidMount' .. 我想是时候睡觉了。


Yoh*_*han 5

就我而言,我要求componentDidMount()从服务(API 调用)检索数据,并且在渲染函数上我有一些组件应该使用从此调用返回的数据。

但是因为调用是异步的,所以render()函数被立即调用,然后崩溃(许多错误,例如:)"TypeError:cannot read property 'XXXX' of undefined"然后看起来componentDidMount根本没有被调用。

为了解决这个问题,我在返回组件本身之前检查渲染myData !== null- 在这种情况下,您可以使用通用 loader\spinner ,它不会渲染在实际从服务检索的数据之前使用数据的内部组件。

例子:

componentDidMount() {
    const { GetMyDataFromServiceFunc } = this.props;

    GetMyDataFromServiceFunc ("150288");
}

render() {
    const { details, loading } = this.props;
    
    if (!details)
        return (<GenericLoader />);
        
        return (

        <FullScreenModal
            <Wizard className="order-new-wizard">

                <Component1 editable={false} dataToComponent1={details}
                    goNextStep={this.goNextStep} /> 

                <Component2 values={details.customerDetail} goNextStep={this.goNextStep} />
            </Wizard>
        </FullScreenModal>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)