【问题标题】:React conditional rendering not updating state in child component反应条件渲染不更新子组件中的状态
【发布时间】:2017-08-11 10:13:35
【问题描述】:

我在条件渲染中遇到了一个奇怪的问题,其中状态不会进入子组件。我有一个查看器模板,带有一个 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 中触发的事件击中,但componentWillReceivePropsshouldComponentUpdatewillComponentUpdate 都没有在PDFWebViewer 内部调用。我怀疑这与render 中的 if/else 块有关,但不确定如何实现。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这个问题的答案是父组件被 shouldComponentUpdate 实现阻止更新,该实现没有考虑到搜索查询的新状态。因此,它一直返回 false,从而阻止将状态更新传播到适当的子组件。

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

    解决了。

    如此简单,却又如此令人沮丧。

    【讨论】:

    • 双刃剑,即 shouldCompUpdate :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 2021-01-27
    • 1970-01-01
    • 2017-03-24
    • 2019-04-03
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多