如何渲染NotFound组件react-router-config

时间:2017-11-26 06:37:03

标签: reactjs react-router

我是新手做出反应我想用反应路由器4实现服务器端渲染我正在使用这个包react-router-config来编写普通路由但是我不知道为什么没有发现组件总是不渲染它访问父路由和父路由如果用户未经过身份验证,他们将重定向。未找到未按预期呈现

enter image description here

代码

import Home from './containers/Home';
import PrivateLayout from './containers/PrivateLayout';
import NewTest from './containers/NewTest'
import TestBoard from './containers/TestBoard';
import Profile from './containers/Profile';
import NotFound from './containers/NotFound';
import PublicLayout from './containers/PublicLayout';
export default [
    {
        ...Home,
        path:'/',
        exact:true
    },
    {
        ...PublicLayout,
        routes:[
            {
                ...Profile,
                path:'/@:username',
                exact:true
            },
            {
                ...PrivateLayout,
                routes:[
                    {
                        ...TestBoard,
                        path:'/home',
                        exact:true

                    },
                    {
                        ...NewTest,
                        path:'/test/:username',
                        exact:true
                    }
                ]
            },


        ]
    },
    {
        ...NotFound,
    },
]

index.js

import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import Routes from './Routes';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reduxThunk from 'redux-thunk';
import { renderRoutes } from 'react-router-config';
import { BrowserRouter ,Switch} from 'react-router-dom';
import reducers from './reducers';
import './index.css';
import axios from 'axios';
import { Map } from 'immutable';
import CONFIG from './config'

const axiosInstance = axios.create({
    baseURL:CONFIG.HOST,
    withCredentials: true
});


const INITIAL_STATE = window.INITIAL_STATE || {};

Object
    .keys(INITIAL_STATE)
    .forEach(key => {
        INITIAL_STATE[key] = Map(INITIAL_STATE[key]);
    });


const store = createStore(reducers,INITIAL_STATE, applyMiddleware(reduxThunk.withExtraArgument(axiosInstance)));

window.store = store;

ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>
            <Switch>
               <div>{renderRoutes(Routes)}</div>
            </Switch>
        </BrowserRouter>
    </Provider>
    , document.getElementById('root'));

更新#1

为什么选择不同的布局?

我有共同的标题(或)登录标题,以便在个人资料页面和私人布局组件上显示。要清楚,即使用户已注销也会显示个人资料页面但是私人布局内容将不会显示,它将被重定向

示例导入

import React,{Component} from 'react';


class NotFound extends Component{
    render(){
        return(
            <h1>Not Found</h1>
        )
    }
}

export default {
    component:NotFound
}

更新Zarcode后我得到了一个错误

  

index.js:2177警告:React无法识别computedMatch   支持DOM元素。如果你故意想让它出现在   DOM作为自定义属性,拼写为小写computedmatch   代替。如果您不小心从父组件传递了它,请删除   它来自DOM元素。       在div中(在index.js:39)       在Switch中(在index.js:38)       在路由器中(由BrowserRouter创建)       在BrowserRouter中(在index.js:37)       在提供者(在index.js:36)

HTML渲染看起来像这样

enter image description here

更新#2

我注意到有线行为如果我更改了私有路由中的notFound组件它正在工作但问题是它只适用于Logged in Routes。

...
    {
                ...PrivateLayout,
                routes:[
                    {
                        ...TestBoard,
                        path:'/home',
                        exact:true

                    },
                    {
                        ...NewTest,
                        path:'/test/:username',
                        exact:true
                    },
                    {
                        ...NotFound,
                    },
                ]
            }
...

3 个答案:

答案 0 :(得分:6)

确保在渲染时将路径包裹在<Switch>中:

  <BrowserRouter>
    <Switch>
       {renderRoutes(routes)}
    </Switch>
  </BrowserRouter>

修改

您应该将路径添加到PublicLayout,因为没有路径的路线始终匹配(因为您可以阅读here),并且不要让您的NotFound始终匹配。

答案 1 :(得分:0)

NotFound永远不会被渲染,因为它总是首先匹配PublicLayout的路径。

我建议添加命名空间,例如:

答案 2 :(得分:0)

其中一条路线

      <?xml version="1.0" encoding="utf-8" ?>
     <configuration>
     <system.web>
     <compilation debug ="true">
    </compilation>
    <authentication mode="None" />
    <httpRuntime maxRequestLength="2097151"  enable = "True" 
    executionTimeout="45"/>
    </system.web>

     <appSettings>

    <add key="MaxThreadsCount" value="3" />
    <add key="CleanupThreadInterval" value="120000" />
    <add key="RequestRetryThreadInterval" value="10000" />
    <add key="InvokeCallsonThread" value="Y" />
    <add key="ThreadKillInterval" value="30" />
  </appSettings>

    <system.serviceModel>
     <services>
      <service name="HierarchyMgntService" behaviorConfiguration="MTServiceBehavior">
        <endpoint name="HIERARCHYMGNTSERVICE" address="http://Example/HIERARCHYMGNTSERVICE/Service.svc" binding="customBinding"
                            bindingConfiguration="HttpBinding" contract="iHierarchyMgnt" />


        <endpoint name="MWServicemexEndpt" address="mex"
           binding="mexHttpBinding"
           contract="IMetadataExchange" />

      </service>
    </services>


    <bindings>
      <customBinding>
        <binding name="HttpBinding"  openTimeout="10:00:00"
                  sendTimeout="10:00:00" receiveTimeout="10:00:00" closeTimeout="10:00:00">
          <binaryMessageEncoding>
            <readerQuotas maxDepth="4194304" maxStringContentLength="2147483647"
                          maxArrayLength="2147483647" maxBytesPerRead="4194304"
                          maxNameTableCharCount="4194304" />
          </binaryMessageEncoding>
          <httpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
        </binding>
      </customBinding>
    </bindings>

    <behaviors>
      <endpointBehaviors>
        <behavior name="ClientBehavior">
          <dataContractSerializer maxItemsInObjectGraph="10485760"/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="MTServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="True" />
          <dataContractSerializer maxItemsInObjectGraph="10485760" />
          <serviceThrottling maxConcurrentCalls="75" maxConcurrentSessions="75"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <!-- Below Log entries message will be true when want to debug any issues otherwise it should be False-->
    <diagnostics>
      <messageLogging
           logEntireMessage="False" logMalformedMessages="False"
           logMessagesAtServiceLevel="False" logMessagesAtTransportLevel="False"
           maxMessagesToLog="5000" maxSizeOfMessageToLog="4194304"/>
    </diagnostics>

  </system.serviceModel>

  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="messages"
               type="System.Diagnostics.XmlWriterTraceListener"
               initializeData="C:\WCFlogs\Messages.svclog" />
        </listeners>
      </source>
      <source name="System.ServiceModel" switchValue="Warning" propagateActivity="true">
        <listeners>
          <add type="System.Diagnostics.XmlWriterTraceListener"
                name="traceListener"
                initializeData="C:\WCFlogs\Traces.svclog"/>
        </listeners>
      </source>
    </sources>
  </system.diagnostics>

</configuration>

内部renderRoutes的工作方式与普通的react-router

相同
  {
    path: '/pathanme/',
    exact: true,
    strict: true,
    check: routeService.check.auth(),
    name: 'routeName',
    component: componentName,
    cache: 0,
  }

这就是渲染路线如何在内部工作。

我在&lt;中添加了一个渲染道具。路线&gt; 您可以在哪里修改自己的逻辑。我已经从名为 check 的路径中再传递了一个属性,我正在检查用户是否已登录。因此,我正在加载组件。