简体   繁体   English

如何从非反应环境中更新组件?

[英]How to update component from non-React environment?

I have most of my html code generated by server, but some things are much faster and easier to do in client with React so I need to create Component not in #root , but somewhere deep inside of my page. 我的大部分html代码都是由服务器生成的,但是在React中使用客户端可以更快,更轻松地完成某些工作,因此我需要创建的组件不在#root ,而是在页面的深处。 The nature of my application is that after the page is loaded it needs to retrieve data via API and it does it 5-6 times in a row with some small pause between each of requests. 我的应用程序的性质是,页面加载后需要通过API检索数据,并且它连续执行5-6次,每个请求之间都有一些暂停。 This normally takes from 10 to 30 seconds. 这通常需要10到30秒。

On the first request I can just check if element is not rendered yet and render it normally: 在第一个请求上,我可以检查元素是否尚未渲染并正常渲染:

if('sorter' in window === false) {
    window.sorter = preactRender(<Sorter filterBoundaries={window.filters} />, document.querySelector('.sorter-holder'))
}

But then I need to send new props to <Sorter /> in order to update it with newly arrived data. 但是然后我需要向<Sorter />发送新的道具,以便使用新到达的数据对其进行更新。 But how could I do it? 但是我该怎么办呢? I tried to do window.sorter.forceUpdate() , but it doesn't work because React's render method returns Element , which obviously doesn't have method forceUpdate() . 我试图做window.sorter.forceUpdate() ,但是它不起作用,因为React的render方法返回Element ,而后者显然没有方法forceUpdate()

Maybe it would be a lot easier to remove old component and render it anew from the scratch? 也许删除旧组件并从头开始重新渲染它会容易得多? Even if it's anti-patern. 即使是反模式。

I just sorted it out simply. 我只是简单地整理了一下。 I added to my application a global variable indicating if sorter needs and update: 我向应用程序添加了一个全局变量,该变量指示排序器是否需要和更新:

if('sorter' in window === false) {
    window.sorter = preactRender(<Sorter filterBoundaries={window.filters} />, document.querySelector('.sorter-holder'))
} else {
    window.sorterUpdatePending = true
}

Then in my component I created an interval to check whether sorter update is pending or not. 然后,在我的组件中,我创建了一个时间间隔,以检查排序程序更新是否正在挂起。 When it is - force an update and reset global variable. 当它是-强制更新并重置全局变量。 And when search is finished it clears the interval. 搜索完成后,它将清除间隔。

componentDidMount() {
    var checkInterval = setInterval(() => {
        if(window.sorterUpdatePending === true) {
            this.forceUpdate()
            window.sorterUpdatePending = false
        }

        if(window.isSearching === false) {
            clearInterval(checkInterval)
        }
    }, 100)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM