安装react组件时未调用componentDidMount()

时间:2016-03-09 15:08:21

标签: reactjs

我一直在尝试从服务器获取一些数据,并且出于某种奇怪的原因componentDidMount()没有按原样发射。我在console.log()内添加了componentDidMount()语句来检查它是否正在触发。我知道对服务器的请求是正常的,因为我在反应之外使用它并且它按预期工作。

class App extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      obj: {}
    };
  };

  getAllStarShips () {
    reachGraphQL('http://localhost:4000/', `{
     allStarships(first: 7) {
       edges {
         node {
           id
           name
           model
           costInCredits
           pilotConnection {
             edges {
               node {
                 ...pilotFragment
               }
             }
           }
         }
       }
     }
    }
    fragment pilotFragment on Person {
     name
     homeworld { name }
   }`, {}). then((data) => {
     console.log('getALL:', JSON.stringify(data, null, 2))
      this.setState({
        obj: data
      });
   });
  }

  componentDidMount() {
    console.log('Check to see if firing')
    this.getAllStarShips();
  }

  render() {
    console.log('state:',JSON.stringify(this.state.obj, null, 2));
  return (
    <div>
      <h1>React-Reach!</h1>
      <p>{this.state.obj.allStarships.edges[1].node.name}</p>
    </div>
  );
}

}

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

4 个答案:

答案 0 :(得分:12)

这里的问题是渲染方法崩溃,因为以下行生成错误

<p>{this.state.obj.allStarships.edges[1].node.name}</p>

修正此问题不要直接使用this.state.obj.allStarships.edges [1] .node.name,除非你能保证每个接收者都被定义。

答案 1 :(得分:1)

检查组件的键

另一件事会导致这种情况发生,如果您的组件没有密钥。在React中,键属性用于确定更改只是组件的新属性还是更改是新组件。

如果密钥发生更改,React将仅卸载旧组件并安装新组件。如果您看到未调用componentDidMount()的情况,请确保您的组件具有唯一键。

设置了键后,React会将它们解释为不同的组件,并进行拆装。

没有密钥的示例:

<SomeComponent prop1={foo} />

带有键的示例

const key = foo.getUniqueId()
<SomeComponent key={key} prop1={foo} />

答案 2 :(得分:0)

我遇到了这个问题(未调用componentDidMount()),因为我的组件正在向构造函数中的组件状态添加属性,而不是在Component声明中。它导致运行时失败。

问题:

class Abc extends React.Component<props, {}> {
    this.state = { newAttr: false }; ...

修复:

class Abc extends React.Component<props, {newAttr: boolean}> {
    this.state = { newAttr: false }; ...

答案 3 :(得分:0)

如果您有一个包含大量代码的组件,还要检查您的 componentDidMount 是否不止一个。在构造函数之后将生命周期方法保持在顶部附近是个好主意。

相关问题