reactjs 需要帮助理解Django项目中react build工件的工作

xzabzqsa  于 5个月前  发布在  React
关注(0)|答案(2)|浏览(35)

我有一个Django后端,我已经粘贴了react项目的构建目录(运行npm run build后).我看到通过代码打开时,react项目的一堆网页打开,即<Link className='dropdown-item' to='/customer/dashboard'>Dashboard</Link>打开<Route path="/customer/dashboard" element={<Dashboard />} />路由的组件(即 Jmeter 板组件启动)。但是如果我将URL更新为http://127.0.0.1:8000/customer/dashboard,甚至使用上述URL刷新页面,我得到404错误。我也有另一个问题,有些网页甚至不通过代码打开。所以我想知道为什么这可能是。
以下是我在urls.py(Django项目)中的代码片段

path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
path('', views.index, name = 'index'),

字符串

views.py

from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache

index = never_cache(TemplateView.as_view(template_name='index.html'))

brqmpdu1

brqmpdu11#

你应该防止客户端路由到达服务器。使用**<HashRouter>**[react router docs]封装所有路由。

6vl6ewon

6vl6ewon2#

根据我的理解,我建议以下方法是处理Django的标准方法url.py

from django.contrib import admin
from django.urls import path,include,re_path
from django.conf import settings
from django.conf.urls.static import static

from django.views.generic import TemplateView

from django.conf  import settings
urlpatterns = [
    # Sample routes:
    path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),#yours
    path('admin/', admin.site.urls), # Admin Route
    path('api/', include('api.urls')), # Other Project route

]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Handle static and media files 
urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] # Handle all other routes with React.. I mean all routes that are not defined above

字符串
上面的代码片段对于大多数用例都是动态的。
在React中,我建议使用Browser Router。这两种组合在生产中也很好用。

相关问题