[英]Calling unstated function using componentDidMount or from another file
I am trying to create a context to store all the info needed for my app, the code below works but I do have limitations, this is Api.js
where I want to put all the logic and API requests/responses. 我正在尝试创建一个上下文来存储我的应用程序所需的所有信息,下面的代码可以工作,但我确实有限制,这是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;
This App.js
<Routes />
is a basic react router with few paths 这个App.js<Routes />
是一个路径很少的基本反应路由器
<Api.Provider inject={[Api.Instance]}>
<Routes />
</Api.Provider>
On components I can use the context but only in render method like so : 在组件上我可以使用上下文,但只能在渲染方法中使用,如下所示:
<Api.Subscribe to={[Api.Instance]}>
{api => (
<p>String(api.state.loggedIn)</p>
<button onClick={() => api.auth()}>run</button>
)}
</Api.Subscribe>
Now my goal is to either implement a componentDidMount
in the APIContainer
or access the function on any component, I tried with props didn't worked! 现在我的目标是在APIContainer
实现componentDidMount
或访问任何组件上的函数,我尝试使用props没有用!
componentDidMount = () => {
this.props.api.auth();
}
Please advise 请指教
As your code, the api.auth()
just valid inside Subscribe, it is invalid at componentDidMount
. 作为您的代码, api.auth()
在Subscribe内部有效,在componentDidMount
无效。
If you want to auto-auth at componentDidMount
, you should make a child component, and pass auth()
to it. 如果要在componentDidMount
上自动验证,则应创建子组件,并将auth()
传递给它。
I made an example for you. 我为你做了一个例子。 You can see that you want on the console. 您可以在控制台上看到您想要的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.