4

リアクションルータv3では、サーバサイドのレンダリングが現在のURLと一致しなかったことがわかりました。これにより、レンダリングされたアプリケーションを送信する代わりに、私のexpress.staticミドルウェアにリクエストを渡すことができました。サーバレンダリングリアルータv4パススルー404

に反応し、ルータをV4、我々はサーバー側でレンダリングするために

const htmlData = renderToString(
     <StaticRouter 
      location={req.url} 
      context={context} 
     > 
      <App/> 
     </StaticRouter> 
    ); 

を使用する必要があります。ただし、すべて自動的にすべてを/にリダイレクトします。この現象はなぜ存在するのでしょうか?黙って失敗したと思われるようなエラーはありませんか?

私はnext()に電話して、他のエクスプレスのルートを仕事にすることができるように、何も一致していないことをどのように知ることができましたか?

は、ここで私が使用したい関数全体である:

app.get('*', (req, res, next) => { 
    const context = {}; 
    const htmlData = renderToString(
     <StaticRouter 
      location={req.url} 
      context={context} 
     > 
      <App/> 
     </StaticRouter> 
    ); 

    console.log(JSON.stringify(context, null, 4)); // empty object 
    if (context.url) { // <------------------------ Doesn't work (taken from example and thought it would contain the unmatched url) 
     winston.info(`Passing ${req.url} along`); 
     next(); // <--------------- Never called even if no route matches. 
    } else { 
     res.send(pageContent.replace('<div id="main"></div>', 
      `<div id="main">${htmlData}</div>`)); 
    } 
}); 

私はthisに基づくものをやってみましたが、// somewhere elseはとても正確で、私はまったく理解できませんでした。

これは私の最後の試みです。これは私がRouteをすべて定義することを計画しているRouter.jsxファイルです。

import React from 'react'; 
import PropTypes from 'prop-types'; 
import { 
    BrowserRouter, 
    Route, 
} from 'react-router-dom'; 
import App from './components/App.jsx'; 

export const Status = ({ code, children }) => (
    <Route render={({ staticContext }) => { 
     if (staticContext) { 
      staticContext.status = code; 
     } 
     return children; 
    }}/> 
); 

Status.propTypes = { 
    code  : PropTypes.number.isRequired, 
    children : PropTypes.node.isRequired, 
}; 

export const NotFound =() => (
    <Status code={404}> 
     <div> 
      <h1>Sorry, can’t find that.</h1> 
     </div> 
    </Status> 
); 

class Router extends React.Component { 
    render() { 
     return (
      <BrowserRouter> 
       <div> 
        <Route exact path="/" component={App}/> 
        <Route component={NotFound}/> 
       </div> 
      </BrowserRouter> 
     ); 
    } 
} 

export default Router; 

(私は、私はこれを約Router.jsxを気にせずに、すべてのStaticRouterが直接App使用していますので、どんな意味がありません知っているが、私はので、私は本当に物事を行う方法を理解していない全くApp内部にはRouteを持っていません推測する。

答えて

1

をあなたは全く使用していない、あなたのApp.jsxファイルではなく、Route.jsx内NotFoundPageコンポーネントルートロジックを置く必要があります。

<Switch> 
    <Route exact path="/" component={AppRootComponent}/> 
    <Route component={NotFound}/> 
</Switch> 

をこれに加えて、このtutorial codeは、リアクションルータv4を使用したサーバー側のレンダリングに最適です。

+0

私のルーティングはルータの代わりにアプリケーションの内部で定義する必要がありますか?ルーターは ''を実行しますか? – Telokis

関連する問題