2016-08-27 4 views
2

저는 반응과 반응 라우터가 새로 도입되었습니다.반응 라우터 "정의되지 않은 '푸시'속성을 읽을 수 없습니다.

반응이있는 문제는 내 응용 프로그램의 일부 페이지에서 반응 라우터가 작동하고 일부에서 다음과 같은 오류가 발생합니다. "속성 '푸시'가 정의되지 않음 '을 읽을 수 없습니다. 내가 사용하고

은 0.14.1

내 라우팅 코드는 다음과 같습니다 반응 :

render(
<Router history={hashHistory}> 
    <Route path="/" component={Loginpanel}/> 
    <Route path="Index" component={Index}/> 
    <Route path="Form" component={Form} /> 
    <Route path="Checkindex" component={Index}/> 

    <Route path="Signup" component={Signup}/> 
    <Route path="Admin" component={Admin}/> 
    <Route path="AdminEditDetails" component={AdminEditDetails}/> 
    <Route path="AdminDetails" component={AdminDetails}/> 


</Router>, 
document.getElementById('js-main')); 

내 구성 요소는 지금과 같다 :

class App extends React.Component { 

    constructor(props) { 
    super(props); 
    this.state= {  
     comments: AppStore.getAll(); 
    }; 
    } 

    componentWillMount() { 
    var length = this.state.comments.length; 
    var firstnumber = length - 4; 

    if(length == 0){ 
     console.log("here comes"); 
     this.props.router.push('/'); 
    } 
    else{ 
     console.log('work normally'); 
    } 
    } 

} 

는 사람이 좀 도와 줄래? 감사.

답변

2

귀하의 앱에는 Cannot read property 'push' of undefined을 제공하는 소품에 라우터 인스턴스가 없습니다. 난 당신이 아직도을 사용하려는 경우 해당에 구성 요소를 포장해야하는 것 때문에 라우터의 인스턴스를 얻을 수 withRouter을 가져 오는 있으리라 믿고있어

(예를 here하지만 권장하지 않음)

대신 프로그래밍 방식으로 탐색하는 더 나은 방법은 componentWillMount주기주기 이벤트에

import { hashHistory } from 'react-router;' ... hashHistory.push('/');을 사용하는 것입니다.

워드 프로세서이 도움이 here

희망입니다!

0

당신이 아래의 코드를 시도 할 수 있습니다 볼 react-router은 확실히 선택 사항이지만 유닛 테스트는 좀 더 고통 스럽습니다. 브라우저 기록은 일반적으로 실행되는 컨텍스트 테스트에서 사용할 수 없으며 글로벌 API를 조롱하는 것보다 소품을 조롱하는 것이 더 쉽습니다.

react-router (v2.4.0부터)이 제공하는 withRouter 상위 구성 요소를 사용하는 것이 좋습니다.

import { withRouter } from 'react-router'; 

class App extends Component { 

    (...) 

} 

export default withRouter(App); 

귀하의 App 클래스는 소품을 통해 router 수신기하고 안전하게 this.props.router.push('/'); 할 수 있습니다.

2

직접 hashHistory를 사용하여 URL을 아래에서 더 많은 정보를 얻기 위해 자신의 문서를 방문 할 수 있습니다

componentWillMount() { 

var length = this.state.comments.length; 
var firstnumber = length - 4; 
if(length == 0){ 
    console.log("here comes"); 
    if(this.props.router !== undefined) { 
    this.props.router.push('/'); 
    } else { 
    console.log(this.props.router); 
    } 
} 
else{ 
    console.log('work normally'); 
} 
} 

을 작업하거나하지 않는 경우

<Route path="/" component={App}> 
+0

허용 된 답변보다 나은 접근 방법입니까? – Doug

+1

@Doug 개인적으로 그렇게 생각합니다.하지만 YMMV는 게시했습니다. :) – ivarni

관련 문제