【问题标题】:React - Django page is blank on refreshReact - 刷新时 Django 页面为空白
【发布时间】:2021-04-15 04:32:30
【问题描述】:

您好,我使用 Django 作为后端,使用 React 作为前端。当我刷新页面并且我不在根页面'/' 上时出现问题,页面变为空白。此外,如果我想立即去其他地方,那么主页,如/contact,它也是空白的。我知道这是因为没有像here 所说的那样联系后端服务器。我试图用useHistory 修复它,但它没有显示useContext 错误。 使用 Django - React 堆栈解决此问题的最佳方法是什么?

主 urls.py:

    urlpatterns = [
       ...
       path('', TemplateView.as_view(template_name='index.html'))
    ]

应用 urls.py:

router = routers.DefaultRouter()
router.register('frontpage', FrontpageViewSet, 'frontpage')
router.register('gallery', GalleryViewSet, 'gallery')
urlpatterns = router.urls

反应 index.js:

import {BrowserRouter} from "react-router-dom";

ReactDOM.render(
    <React.StrictMode>
        <BrowserRouter>
            <App/>
        </BrowserRouter>
    </React.StrictMode>,
document.getElementById('root')
);

App.js:

const location = useLocation();
return (
    <div className="App">
        <GlobalStyle/>
        <Nav/>
        <Switch location={location} key={location.pathname}>
            <Route exact path='/'>
                <HomePage/>
            </Route>
            <Route exact path='/gallery'>
                <GalleryPage/>
            </Route>
            <Route exact path='/contact'>
                <ContactPage/>
            </Route>
        </Switch>
    </div>
);

【问题讨论】:

    标签: python reactjs django url routes


    【解决方案1】:

    我通过将 useHistory 放入所有页面并在页面加载时使用 useEffect 加载它来修复。

    【讨论】:

    • 你是如何将 react 与 django rest 框架连接起来的?
    • 使用 django rest 框架,您可以创建 REST API 端点。然后,您只需向该 API 端点发送请求。你可以尝试谷歌一些这样的教程:geeksforgeeks.org/how-to-connect-django-with-reactjs
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2017-02-21
    • 2020-05-22
    • 1970-01-01
    • 2021-08-22
    • 2023-01-29
    • 2013-12-15
    相关资源
    最近更新 更多