首页 > 解决方案 > 在另一个组件中渲染 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)

标签: reactjstypescriptreact-typescript

解决方案


您需要将提供程序包装在 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>
);

推荐阅读