2017-08-08 296 views
1

我想從基礎部件推到另一個在被作爲PARAMS與history.push底部組件定義了一些數據怪異的行爲。通過this.props.history.push傳遞的數據已在目標頁面

Base Component

class BaseComponent extends React.Component 
{ 
    gotoTargetPage() 
    { 
     const params = { data: {fname: 'john', lname: 'doe' } }; 
     this.props.history.push('/target-page', params); 
    } 

    render() 
    { 
     return(<button onClick={event => this.gotoTargetPage()}>Go!</button>) 
    } 
} 

export default withRouter(BaseComponent); 

TargetPage Component:

class TargetComponent extends React.Component 
{ 
    componentDidMount() 
    { 
     console.log(this.props.history.location.state.data); 
    } 

    render() 
    { 
     return(<div>Hi! I am {this.props.history.location.state.data.fname}.</div>) 
    } 
} 

當我點擊底部組件上的按鈕,它成功地加載目標頁面。但控制檯日誌this.props.history.stateundefined,它呈現不帶參數的數據(因爲它不可用)。

這裏的扭曲。如果我刷新頁面,我可以看到顯示的數據和控制檯正確記錄數據。不只是如果我刷新,但如果我點擊後退按鈕(第一步後),數據顯示和控制檯記錄數據。此外,這大約發生在75%的時間,大約四分之一的嘗試發生時沒有任何問題。

我重複相同的情況下創造新的成分,但具有相同的結果。這可能是什麼原因?

Environment:

"react": "^15.5.4", 
"react-router": "^4.1.1" 

回答

2

我想你可能會結合history.push()兩個簽名(見https://github.com/reacttraining/history

要麼你傳遞一個路徑URL和一個可選的狀態對象

history.push('/some/path', { some: 'state' }) 

或者您將所有內容都傳遞給一個對象

history.push({ 
    pathname: '/home', 
    state: { some: 'state' } 
}) 
+0

我非常抱歉。試圖重現問題時,我不小心錯位了花括號。我嘗試了這兩種選擇,但結果完全相同。 – anonym

+0

是通過「」呈現的TargetComponent? – Tony

+0

是的。像這樣:'' – anonym

0

問題是由於某些其他原因再次重新渲染組件,則道具會丟失發送的參數,因此設置爲this.props.history.location = undefined。以下方法適用於我。

/** 
* When component mounts, grab the params if there is any and setState 
*/ 
componentWillMount() 
{ 
    // when params sent via url 
    if (this.props.history.location.state) 
    { 
     let params = this.props.history.location.state; 
     this.setState({ params }); 
    } 
} 

由於數據現在存儲在組件狀態,因此不會丟失,並且無處不在。