reactjs - 在另一个组件中渲染 App.tsx 类
问题描述
大家好,这是我用打字稿做出反应的项目设置
索引.ts
import React from "react";
import { BrowserRouter } from "react-router-dom";
import { App } from "./app";
const rootStore=new RootStore()
const root = document.getElementById("root");
const Application = (
<BrowserRouter>
<App />
</BrowserRouter>
);
应用程序.tsx
import React from 'react'
interface Props {
authStore?: AuthStore;
}
const rootStore=new RootStore()
@inject('authStore')
@observer
export class App extends React.Component<Props> {
constructor(props: Props) {
super(props)
makeObservable(this)
}
@observable private isModalOpen = false;
render() {
return (
<Provider {...rootStore}>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/contact-us" component={ContactUsComponent} />
<Route path="/about-us" component={AboutUsComponent} />
<Route exact path="/admin/sign-up" component={Signup} />
<Route exact path="/admin/sign-in" component={Login} />
<PrivateRoute component={AdminDashboard} path="/admin/dashboard" hasPermission={true} />
</Switch>
</Provider>
);
}
}
问题是我在我的项目中使用了 mobx,现在是因为
<PrivateRoute/>
我必须从我的商店访问我的“isAuthenticated”变量,以便我可以将它作为我的道具传递到这里,<PrivateRoute hasPermission/>
但由于 App.tsx 本身没有包含在任何 Provider 标签中,我无法访问商店,所以无论如何我们可以只使用一个我应该可以访问商店的组件,然后返回一些类似的东西
<提供者 {...rootStore}>
除了(index.tsx)
解决方案
您需要将提供程序包装在 index.tsx 中,并且可以从 App.tsx 中删除提供程序。
import React from "react";
import { BrowserRouter } from "react-router-dom";
import { App } from "./app";
const rootStore=createStore()//---> Move your create store to a another file.
const root = document.getElementById("root");
const Application = (
<Provider {...rootStore}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
推荐阅读
- r - 分组,总结两个变量的不同案例
- ios - Swift 5.2 和 UnsafePointer
- python - Pandas 在不同大小的行中求和值
- node.js - 没有从 getIdToken() 获取令牌,但是当我显示文档数据时,它显示 accessToken
- scmmanager - 服务器 2012 上的 scm-manager Windows 服务
- html - Bootstrap 4 较低的屏幕尺寸排序
- c - How do I make my C program count more than just one character?
- flutter - Flutter, not sure how to implement a PageRouteBuilder(), when using a WidgetBuilder to configure my routes
- asp.net - 在 ASP.NET 4.8 和 ASP.NET Core 3.1 之间共享身份验证 cookie
- javascript - 这用于对数组进行排序是如何工作的?