【问题标题】:React Router v4 is rendering blank pages for child components in a React.js SPAReact Router v4 正在为 React.js SPA 中的子组件呈现空白页面
【发布时间】:2017-11-19 17:57:03
【问题描述】:

我们正在将我们的 React SPA 嵌入到一个非根 URL 的网站中。我在设置路由时遇到问题,以便它可以保留页面首次启动的路径。例如,应用程序在 mysite.com/c/{customerId} 加载。进入应用程序并导航到设置页面后,我希望 URL 为 mysite.com/c/{customerId}/settings。

问题: 为什么单击我的链接时呈现的页面完全为空?

以下是我目前的配置,我们使用的是 Typescript、Webpack、React 和 React-Router v4。

输入文件 (index.tsx)

ReactDOM.render(
<BrowserRouter>
    <Switch>
        <Route exact path='/c/:userId' component={App}/>
    </Switch>
</BrowserRouter>
, document.getElementById("root"));

App.tsx

render() {
        return ( 
            <div>
                <Menu/>
                <Sidebar/>
                <ContentPage/>
            </div>
    );
}

contentPage.tsx

render() {   
    return (
           <main className={styles.mainContent}>
               <Switch>
                    <Route path='/c/:userId/settings' component={SettingsPage} />
                    <Route path='/c/:userId/products' component={ProductPage}/>
               </Switch>
           </main>
    );
}

settingsPage.tsx

export const SettingsPage = () => {
    return ( 
            <Switch>
                <Route path='/c/:userId/settings' component={SettingsMain}/>
                <Route path='/c/:userId/settings/:gameId' component={GameEdit}/>
                <Route path='/c/:userId/settings/:gameId/levels' component={LevelsEdit}/>
            </Switch>
);

sidebar.tsx(链接的位置)

<Link to={`/c/${this.state.userId}/settings`} className={styles.sidebarItem}>
                            <i className={styles.sidebarIcon + " fa fa-cloud-upload"}></i><br/>
                            Settings
                    </Link>

设置主界面

export class SettingsMain extends React.Component<Props, State> {

public render() {
   return (
        <div>
           <h4>This is a Settings page</h4>
       </div>
);

}

【问题讨论】:

  • SettingsMain 是什么样的?
  • 是否定义了this.state.userId
  • 我已经用 SettingsMain 更新了我的帖子。 this.state.userId 似乎已定义。如果我在 App 类中的断点处停止,它似乎在 this.props.match.params.userId 中初始化

标签: javascript reactjs typescript react-router react-router-v4


【解决方案1】:

解决方案是使用 BrowserRouter 中的 basename 属性。一旦我设置了它并从我的路由中删除了基本 URL,一切就开始工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2021-08-16
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2019-05-31
    相关资源
    最近更新 更多