简体   繁体   English

在非反应组件中调用App的forceUpdate而不将App作为属性传递

[英]Call App's forceUpdate in a non react component without passing App as property

I have a module which is not a react component (let's call it A) but its variables get displayed by react. 我有一个模块,它不是React组件(我们称它为A),但是它的变量由react显示。 Now A has to call the forceUpdate function of App.js. 现在,A必须调用App.js的forceUpdate函数。 But I don't want to pass always App.js as a property when I create a new object of A. 但是我不想在创建A的新对象时始终将App.js作为属性传递。

I've created following: 我创建了以下内容:

App.js: App.js:

let forceUpdateCaller;

export default class App extends React.Component {

    static forceUpdate = () => {
        if (forceUpdateCaller) {
            forceUpdateCaller();
        }
    }

    forceUpdateCaller = () => {
        this.forceUpdate();
    }

    constructor(props) {
        super(props);        

        forceUpdateCaller = this.forceUpdateCaller;
    }

    ...

}

A: A:

import App from "../App";

export default class A extends ...{

    constructor() {
        super();
    }

    updateContent = () => {

        ...

        App.forceUpdate();
    }
}

But I'm sure, there's a better, cleaner way. 但我敢肯定,有一种更好,更清洁的方法。 Do you have any ideas? 你有什么想法?

Found the best way: 找到了最好的方法:

export let ref;

class App extend React.Component{
    constructor(props){
        super(props);
        ref = this;
    }
}

Now I have full access to the App object when I import {ref} . 现在,我在导入{ref}时可以完全访问App对象。 :) :)

暂无
暂无

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

相关问题 如何在没有forceupdate的情况下让反应组件重新渲染? - How to get a react component to rerender without forceupdate? 如何在render()的JSX组件树中定义的组件上调用React forceUpdate() - How to call React forceUpdate() on the component that is defined in JSX component tree in render() 反应警告:无法在未安装的组件上调用 setState(或 forceUpdate) - React Warning: Can't call setState (or forceUpdate) on an unmounted component 警告:无法在React Native中的已卸载组件上调用setState(或forceUpdate) - Warning: Can't call setState (or forceUpdate) on an unmounted component in React Native 反应-警告:无法在未安装的组件上调用setState(或forceUpdate) - React - Warning: Can't call setState (or forceUpdate) on an unmounted component 无法在已卸载的组件上调用setState(或forceUpdate)。 应对 - Can't call setState (or forceUpdate) on an unmounted component. React 将数据传递到现有应用程序中的 React 组件 - Passing data into a React component within existing app 当redux状态更新时,在组件上调用forceUpdate() - call forceUpdate() on component when redux state updates 无法在卸载的组件上调用setState(或forceUpdate) - Can't call setState (or forceUpdate) on an unmounted component 如何解决:无法在 React-Native 中的未挂载组件警告上调用 setState(或 forceUpdate)? - How to solve: Can't call setState(or forceUpdate) on an unmounted component warning in React-Native?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM