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

ken*_*igo 13 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')
);
Run Code Online (Sandbox Code Playgroud)

Jim*_*did 14

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

<p>{this.state.obj.allStarships.edges[1].node.name}</p>
Run Code Online (Sandbox Code Playgroud)

修复此问题直接不使用this.state.obj.allStarships.edges [1] .node.name,除非您可以保证每个接收器都已定义.


Jon*_*Jon 6

检查组件的密钥

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

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

使用密钥集,React 会将它们解释为不同的组件并处理卸载和安装。

没有钥匙的例子:

<SomeComponent prop1={foo} />
Run Code Online (Sandbox Code Playgroud)

带钥匙的例子

const key = foo.getUniqueId()
<SomeComponent key={key} prop1={foo} />
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这正是我的组件未更新的问题所在。我寻找答案很长时间。 (3认同)