2017-08-11 89 views
0

我有一个奇怪的问题,有条件的渲染,其中状态是'下降到子组件。我有一个查看器模板,带有PDF查看器组件和Web查看器组件(使用iframe)。根据从服务器返回的值作为media_type值,合适的组件将被渲染。这一切工作正常。反应有条件的渲染没有更新子组件中的状态

从外部看,我有一个兄弟组件负责在内容中搜索,为此,它必须将搜索查询传递给父组件,父组件然后更新父状态,然后传递给孩子作为道具。原因是不同的内容需要不同的搜索实现,这是在查看器组件内部实现的。

显然,我的条件呈现方法是打破子组件中的搜索查询prop更新。当prop更改时,没有任何组件更新方法被调用,因此搜索执行永远不会被调用。

同级组件调用的公共父这个方法:

/** 
* Search query execution handler. Passes the state as a prop to the catalog for search 
* execution 
* @param e Keyword or query string from SearchPanel 
*/ 
searchQueryHandler(e) { 
    this.setState({ 
     searchRequest: e 
    }); 
} 

父组件渲染方法

render() { 

    let viewer = <div />; 

    if (this.state.link.media_type === 1) 
     viewer = <PDF file={this.state.link.id} 
         setOverlayVisibility={this.props.setOverlayVisibility} 
         searchQuery = {this.state.searchRequest} 
         searchMatchHandler={this.searchMatchHandler} 
         searchResultSelection={this.state.searchResultSelection} 
     />; 
    else if (this.state.link.media_type !== '') 
     viewer = <WebViewer link={this.state.link} 
           setOverlayVisibility={this.props.setOverlayVisibility} 
           searchQuery={this.state.searchRequest} 

     />; 

    return (
     <Content> 
      <ContentLeft> 
       {viewer} 
      </ContentLeft> 
      <ContentRight> 
       <SidePanel institution={this.state.institution} 
          link={this.state.link} 
          searchQueryHandler={this.searchQueryHandler} 
          searchResults={this.state.searchResults} 
          searchResultClickHandler={this.searchResultClickHandler} 
       /> 
      </ContentRight> 
     </Content> 
    ) 
} 

现在,searchQueryHandler方法正被事件命中SidePanel发射了,但componentWillReceiveProps,shouldComponentUpdate,willComponentUpdate均不在PDFWebViewer之内。我怀疑这与render中的if/else块有关,但不知道如何实现它。

回答

0

对此的回答是父组件被阻止更新shouldComponentUpdate实现,该实现没有考虑到搜索查询的新状态。因此,它始终返回false,从而阻止状态更新传播到适当的子组件。

shouldComponentUpdate(nextProps, nextState) { 
    return this.state.link !== nextProps.link || this.state.searchRequest !== nextState.searchRequest; 
} 

是修复。

这么简单,但却令人沮丧。

+0

是应该更新的双刃剑:) –