如何强制React组件重新渲染?

pan*_*kaj 0 javascript bootstrap-modal reactjs

我们正在开发一个 POC,其中显示属性列表,并在单击属性标题时在引导模式弹出窗口中显示相应的属性详细信息。

我们有以下具有层次结构的 React 组件:

1 个属性框

1.1 属性列表

1.1.1 属性信息

1.2 Bootstrap Modal 弹出 HTML 中的 PropertyDetails。

PropertyBox 的 render 方法包​​含以下代码。

render() {
return (
<div id="property-box">
<PropertyListComponent>
<div class="modal fade" id="myModal">
    <div class="modal-dialog modal-lg modal-box-large">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body modal-max-height">
                {propertyDetailsElement}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
</div>;
Run Code Online (Sandbox Code Playgroud)

在属性详细信息组件中,有两个 bootstrap 4 选项卡 1. 概述(默认情况下处于活动状态) 2. 联系我们

问题是,

假设我通过单击“属性”标题打开了属性详细信息弹出窗口,然后转到“联系我们”选项卡并关闭了弹出窗口。

之后,我单击“下一个属性标题”以查看其属性详细信息。在这种情况下,弹出窗口将打开,显示相应的属性详细信息,但“联系我们”选项卡显示为活动状态。

因此,为了解决这个问题,我尝试使用方法“componentWillReceiveProps”重新渲染 PropertyDetails 组件

class PropertyDetail extends React.Component {

    constructor(props) {
        super(props)
        // in state we have stored the images as well as current index of image and translate value
        this.state = {
            property: this.props.data
        }
    }

    componentWillReceiveProps(nextProps) {
        this.setState({
            property: nextProps.data
        })
    }
    render() {return (<HTML for Proeperty Details>);
    }
}

Run Code Online (Sandbox Code Playgroud)

我交叉验证了每次单击 PropertyTitle 打开 Popup 时是否都会调用方法“componentWillReceiveProps”,是的,每次都会调用该方法。但问题并没有解决。

我期望每次打开“属性详细信息”弹出窗口时,默认活动选项卡应该是“概述”选项卡。

有什么解决办法吗?

小智 5

有两种方法可以实现这一目标。

1)当您更改属性时添加一个名为的默认函数

componentWillUnMount它将从 dom 中删除该组件并重置其属性

或者你可以使用

在您的组件中,您可以调用this.forceUpdate()方法来强制重新渲染。

2)第二个是将一个密钥传递给组件,每当您更改时property,它都会更新传递给组件的密钥,因此每次都会打开一个属性,新的密钥将被传递,并且新的组件实例将被打开,您不会再遇到这个问题