Programing

라우터 서버 측면 렌더링 오류 대응: 경고: propType 실패: 필수 prop 'history'가 'RoutingContext'에 지정되지 않음

c10106 2022. 4. 6. 22:20
반응형

라우터 서버 측면 렌더링 오류 대응: 경고: propType 실패: 필수 prop 'history'가 'RoutingContext'에 지정되지 않음

React/Hapi를 배우기 위해 간단한 장난감 앱을 설치하고 있는데 서버사이드 라우팅을 설정하기 전까지 모든 것이 잘 작동하고 있다.서버는 오류 없이 실행되며 "/" hello world를 적절하게 렌더링한다.

그러나 "/테스트"로 이동하면 다음과 같은 오류가 발생한다.

Warning: Failed propType: Required prop `history` was not specified in `RoutingContext`.
Warning: Failed propType: Required prop `location` was not specified in `RoutingContext`.
Warning: Failed propType: Required prop `routes` was not specified in `RoutingContext`.
Warning: Failed propType: Required prop `params` was not specified in `RoutingContext`.
Warning: Failed propType: Required prop `components` was not specified in `RoutingContext`.

내가 어디가 잘못됐지?

서버.js

'use strict';

const Hapi = require('hapi');
const Path = require('path');

const server = new Hapi.Server();
server.connection({ port: 3000});

//React Junk
import React from 'react';
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import { renderToString } from 'react-dom/server';
import reducer from './../common/Reducers/index.js';
import { match, RoutingContext } from 'react-router';
import Routes from './../common/routes/Routes.js';

const handleRender = function(req, res) {
    const store = createStore(reducer);
    match({Routes, location: req.url}, (error, redirectLocation, renderProps) => {
        //res(req.url);
        if(error) {
            res(error.message);
        }
        else {
            const html = renderToString(
            <Provider store={store}>
                <RoutingContext {...renderProps} />
            </Provider>
            );

            const initialState = store.getState();

            res(renderFullPage(html, initialState));
        }

    });
    // const html = renderToString(
    //  <Provider store={store}>
    //      <App />
    //  </Provider>
    // );

    // const initialState = store.getState();

    // res(renderFullPage(html, initialState));
}

const renderFullPage = function(html, initialState) {
    return `
        <!doctype html>
        <html>
            <head>
                <title>Please Work</title>
            </head>
            <body>
                <div id="app-mount">${html}</div>
                <script>
                    window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}
                </script>
                <script src="/static/bundle.js"></script>
            </body>
        </html>
    `;
}

server.register(require('inert'), (err) => {
    server.route({
        method: 'GET',
        path: '/static/{filename}',
        handler: function (req, reply) {
            reply.file('static/' + req.params.filename);
        }
    })
    server.route({
        method: 'GET',
        path: '/',
        handler: function(req, res) {
            res('hello world');
        }
    });
    server.route({
        method: 'GET',
        path: '/{path*}',
        handler: function(req, res) {
            handleRender(req, res);
        }
    })

    server.start(() => {
        console.log('Server running at:', server.info.uri);
    })
})

Route.js

import { Route } from 'react-router';

//Components
import App from './../components/App.jsx';
import Name from './../components/Name.jsx';

export default (
    <Route path="/" component={App}>
        <Route path="test" component={Name} />
    </Route>
);

왜냐하면 그들은 부탁을 받았기 때문이다.

클라이언트 entry.jsx

import React from 'react';
import ReactDOM from 'react-dom';

import {createStore} from 'redux';
import {Provider} from 'react-redux';
import App from './../common/components/App.jsx';
import Router from './../common/routes/Router.jsx';
import reducers from './../common/Reducers';

const initialState = window.__INITIAL_STATE__;
const store = createStore(reducers(initialState));

ReactDOM.render(
    <Provider store={store}>
        <Router />
    </Provider>
, document.getElementById('app-mount'));

클라이언트 라우터

 import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { Router, Route } from 'react-router';
import createHashHistory from 'history/lib/createHashHistory';

const history = createHashHistory();

import Routes from './Routes.js';

export default (
    <Router history={history}>
        <Routes />
    </Router>
);

합격해야 한다.history의 소품으로.Router클라이언트에서:

export default (
    <Router history={history}>
        <Routes />
    </Router>
);

서버 코드에 문제가 있을 수 있는 것은 라우트를 전달하지 않는다는 것이다.match바르게그것은 이름이 붙은 부동산을 기대한다.routes, 아니다.Routes. 다음을 시도해 보십시오.

match({routes: Routes, location: req.url}, (error, redirectLocation, renderProps) => {

특히 설명서에서 다음 문구를 참고하십시오.

If all three parameters are undefined, this means that there was no route found matching the given location.

참조URL: https://stackoverflow.com/questions/34501206/react-router-serverside-rendering-errors-warning-failed-proptype-required-pro

반응형