我'm having a weird problem with conditional rendering in which state isn'进入儿童组成部分 . 我有一个查看器模板,带有PDF查看器组件和Web查看器组件(使用iframe) . 根据从服务器返回的值作为 media_type
值,将呈现相应的组件 . 这一切都很好 .
在外部,我有一个兄弟组件负责在内容中进行搜索,为了做到这一点,它必须将搜索查询传递给父组件,然后父组件更新父状态,然后作为支柱传递给子组件 . 其原因是不同的内容需要不同的搜索实现,这是在查看器组件内部实现的 .
显然,我的条件渲染方法打破了子组件中的搜索查询道具更新 . 当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
中没有一个在 PDF
或 WebViewer
内被调用 . 我怀疑这与 render
中的if / else块有关,但不确定如何实现它 .
1 回答
对此的答案是,由于没有考虑搜索查询的新状态的
shouldComponentUpdate
实现阻止了父组件的更新 . 因此,它一直返回false,从而阻止状态更新传播到适当的子组件 .是修复 .
这么简单,又令人沮丧 .