Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

reactjs - Rendering App.tsx class in Another Component

Hi guys here is my project setup of react with typescript

index.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>
);

App.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>
    );
  }
}

The thing is i was using mobx in my project and now for the reason of

<PrivateRoute/>

I have to get access to my "isAuthenticated" variable from my store so that i can pass it down here as a prop in my <PrivateRoute hasPermission/> but as App.tsx itself is not wrapped in any Provider tag i wont have access to store, so anyway we could just user one component where i should have access to the store and then return some thing like

<Provider {...rootStore}>

except (index.tsx)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to wrap the provider inside the index.tsx and you can remove provider from inside of 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>
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...