导入的功能组件完成后如何更新React组件

时间:2019-06-13 14:27:27

标签: reactjs

在另一个功能组件中完成一个功能后,如何更新组件?

例如,使用以下代码:

myFunctionComponent.tsx

class myFunctionComponent extends React.Component {

    public doSomething = () => {
        console.log('something is done');
    }
}

Page.tsx

class Page extends React.Component {

    import myFunctionComponent = './myFunctionComponent.ts' 

    public componentDidMount() {
        // somehow once this is done
        myFunctionComponent.doSomething();
    }

    public render() {

        // it should update this
        const doSomethingIsDone = false;

        if (doSomethingIsDone) {
            return (<Redirect to="/" />)
        }
    }
}

我想以某种方式通知Page.tsx myFunctionComponent.ts中的doSomething已完成。应该通过回调函数完成此操作吗?

2 个答案:

答案 0 :(得分:1)

通常,在React中,您永远不会与render函数之外的组件进行交互。组件与其他组件直接交互的唯一方法是渲染它们。
在大多数情况下,有两种方法可以实现它们。
如果您能够从myFunctionComponent内部渲染Page,则可以传递一个回调,该回调将在doSomething完成后触发。

export class Page extends React.Component {
  onSomething = () => { 
    // Here you can do what ever you need after `something` happens
   }

  public render() {
    return <MyFunctionComponent onSomething={this.onSomething} />
  }
}

第二种选择是将doSomething提取到一个单独的文件中,将其导入并用作一种类似于服务的功能:

import doSomething from "./do-something";

export class Page extends React.Component {
  onSomething = () => { 
    // Here you can do what ever you need after `something` happens
   }

   componentDidMount() {
     doSomething();
     doSomethingElse();
   }

  public render() {
    const doSomethingIsDone = false;

    if (doSomethingIsDone) {
      return (<Redirect to="/" />)
    }
  }
}

您的第三个选择是使用某种形式的状态容器(例如React ContextReduxMobX)。此选项可能是最冗长的选项,并且提供了最多的功能(取决于您选择的状态库),但是您可能不需要它。

我还建议您阅读React的Lifting State Up指南,因为我认为其中包含许多有用的信息,可能会回答您的问题。

答案 1 :(得分:0)

尝试一下:

myFunctionComponent.tsx

class myFunctionComponent extends React.Component {

    public doSomething = (callback) => {
        console.log('something is done');

        callback();
    }
}

Page.tsx

class Page extends React.Component {

    import myFunctionComponent = './myFunctionComponent.ts' 

    public componentDidMount() {
        // somehow once this is done
        myFunctionComponent.doSomething(this.callback);
    }

    public callback() {
        //Do something finished, refresh component
    }

    public render() {

        // it should update this
        const doSomethingIsDone = false;

        if (doSomethingIsDone) {
            return (<Redirect to="/" />)
        }
    }
}