使用componentDidMount或从另一个文件调用未声明的函数

时间:2019-05-15 12:36:28

标签: reactjs react-context unstated

我正在尝试创建一个上下文来存储我的应用所需的所有信息,下面的代码可以工作,但是我确实有局限性,这是Api.js,我要在其中放置所有逻辑和API请求/响应

import { Provider, Subscribe, Container } from "unstated";
import fire from "./config/Fire";

class APIContainer extends Container {
  constructor(props = {}) {
    super();
    this.state = {
      loggedIn: false,
      loading: null,
    };
  }
  async auth() {
    fire.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({ loggedIn: true, loading: false });
      }
      else {
        this.setState({ loggedIn: false, loading: false });
      }
    });
  }
}

const Api = {
  Instance: new APIContainer(),
  Provider,
  Subscribe
};

export default Api;
  

此App.js <Routes />是具有很少路径的基本React路由器

 <Api.Provider inject={[Api.Instance]}>
    <Routes />
 </Api.Provider>

在组件上,我可以使用上下文,但只能在这样的渲染方法中使用:

<Api.Subscribe to={[Api.Instance]}>
{api => (
   <p>String(api.state.loggedIn)</p>
   <button onClick={() => api.auth()}>run</button>
  )}
 </Api.Subscribe>

现在,我的目标是在componentDidMount中实现APIContainer或访问任何组件上的函数,我尝试使用props无效!

componentDidMount = () => {
 this.props.api.auth();
}

请告知

1 个答案:

答案 0 :(得分:1)

作为您的代码,api.auth()仅在订阅中有效,在componentDidMount处无效。

如果要在componentDidMount处进行自动身份验证,则应制作一个子组件,并将auth()传递给它。

我为你树立了榜样。 您可以在控制台上看到所需的内容。

a unstated example