2017-10-26 21 views
1

history小道具をAppからナビゲーションコンポーネントに渡します。私はそうしようとするとき 、私は次のエラーメッセージが表示されます。コンポーネントにhistory propを渡すことができません

失敗しましたプロップタイプ:Navigationに必要とされる小道具historyがマークされているが、その値はundefinedです。

この問題を解決するにはどうすればよいですか?

App.js:

import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; 

const App = props => (
    <Router> 
     <MainLayout {...props}> 
     <Switch> 
      <Route exact name="index" path="/" component={Index}/> 
      <Route component={NotFound}/> 
     </Switch> 
     </MainLayout> 
    </Router> 
); 

MainLayout.js:

import React from "react"; 
import PropTypes from "prop-types"; 
import Navigation from "../../components/Navigation/Navigation"; 

const MainLayout = props => { 
    const { children, authenticated, history } = props; 

    return (
    <div> 
     <Navigation authenticated={authenticated} history={history} /> 
     {children} 
    </div> 
); 
}; 

MainLayout.PropTypes = { 
    children: PropTypes.node.isRequired, 
    authenticated: PropTypes.bool.isRequired, 
    history: PropTypes.object.isRequired, 
}; 

export default MainLayout; 
+0

は '' MainLayout'の内部値を持つhistory'ていますか?あなたのエラーは、 'Navigation'がそれを取得しているときに' undefined'であることを示唆しています。また、 'App'は'歴史 'の支柱を受けているようだ。その小道具を追跡し、それが通過する前にそれが定義されていることを確認してください。 –

+0

'MainLayout'の中の' history'の値は 'undefined'ですが、 'App'の中には値が割り当てられています –

答えて

2

溶液#1:

あなたは単にあなたがアクセスする必要がありますレンダリング<Route /><MainLayout />を変換する場合履歴オブジェクトに追加します。

<Route render={(props) => 
    <MainLayout {...props}> 
    <Switch> 
     <Route exact name="index" path="/" component={Index}/> 
     <Route component={NotFound}/> 
    </Switch> 
    </MainLayout> 
}/> 

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Route.js

<App />、これはあなたが<MainLayout {...props}>

を欠けているものを溶液#2

を行うことはありませんので、あなたはまた、参照できる小道具として歴史へのアクセス権を持っていませんヒストリーオブジェクトをあなたのアプリで一つのエクスポートされたモジュールとして使用して、あなたのアプリのReactルータとその他のcompopent/javascriptファイルの両方を参照してください。

import { Router, Switch, Route } from 'react-router-dom'; 
import history from './history'; 

const App = props => (
    <Router history={history}> 
     <MainLayout history={history} {...props}> 
     <Switch> 
      <Route exact name="index" path="/" component={Index}/> 
      <Route component={NotFound}/> 
     </Switch> 
     </MainLayout> 
    </Router> 
); 

(history.js)

import createHashHistory from 'history/createBrowserHistory'; 

export default createHashHistory(); 

https://www.npmjs.com/package/history

+0

まずはおかげさまですが、残念ながら私は' onClick = {()=> history.push( "/")} '要素に対して、' Uncaught TypeError:history.pushは関数ではありません。どのように私はそれを解決することができますか? :) –

+0

私の編集はあなたがこのコメントで言及した問題を解決するはずです – Maxwelll

関連する問題