2017-06-12 81 views
1

有一個搜索組件,當有效負載重新定向到結果組件時。希望結果組件使用React Router v4 Redirect來顯示搜索的傳遞狀態。我在這裏從Docs的假設是,使用state: { referrer: currentLocation }可以傳遞一個對象。React路由器v4重定向傳遞狀態從搜索到結果

搜索

export default class Search extends Component{ 
    constructor(props){ 
    super(props); 
     this.state = { 
     searchValue: '', 
     results:[] 
     } 
    this.handleKeyPress = this.handleKeyPress.bind(this); 
    } 

    handleKeyPress = (e) => { 
    let searchParam = e.target.value; 
    if (e.key === 'Enter'){ 
     axios 
     .get(URL+searchParam) 
     .then((response) => { 
      this.setState({results: response.data}); 
     }); 
    } 
    }; 

    render(){ 
    return(
     <div> 
     <input 
      ref="search" 
      type="text" 
      placeholder="Search" 
      onKeyPress={this.handleKeyPress.bind(this)} 
     /> 
     {this.state.results.length > 0 && 
      <Redirect to={{ 
      pathname: '/results', 
      state: { results: this.state.results } 
      }} /> 
     } 
     </div> 
    ); 
    } 
} 

結果

除非我不讀這個正確,這個問題似乎是,當重定向發生沒有什麼是傳遞給結果組件。

如果輸入值並且成功重定向發生搜索狀態返回Object {searchValue: "", results: Array(1)}但是,根據初始狀態設置,搜索結果狀態將返回Object {results: Array(0)}undefined

在結果上也嘗試過不同的組件生命週期,但無法以任何方式獲取任何傳遞的數據。我的想法可能是可能能夠獲得一些通過數據,並可以通過這些手段設置狀態。

回答

0

看起來物體已經通過,但它嵌套在location.state中,看起來不夠深。

2

從主類組件的render()方法的開始,你必須代碼,例如:

if (isLoggedIn){ 
    return <Redirect to={ 
     pathname: '/anyPath', 
     state: { stateName: this.state.anyState} 
    } />; 
} 

,並在相關的路線/anyPath的組件,您必須提取傳遞的狀態調用this.props.location.state.stateName 。在您的確切情況下,您應該在結果分類中致電this.props.location.state.results。您可以從Results類中刪除構造函數方法。

isLoggedIn可能是另一個狀態,您可以在主要組件的構造函數Method中首先設置爲false。然後,如果用戶單擊按鈕,則可以將isLoggedIn設置爲true,因此您將使用首選狀態將您的應用重定向到其他路由。

相關問題