2017-09-01 28 views
0

我嘗試構建一些「google-like-search-input」頁面 - 在輸入改變時,切換到結果頁面並顯示所有搜索結果。reactjs輸入onChange switchRoute但丟失第一個字符

但是,如果我按任何鍵 - 我跳轉到結果頁(#/結果),我失去了我的第一個輸入的字符?

有沒有人提示,我該如何解決這個問題?

class Home extends React.Component { 
    constructor(props, context) { 
    super(props, context); 
    this.state = { 
     query: '' 
    }; 
    this.updateInputValue = this.updateInputValue.bind(this); 
    } 
    updateInputValue(event) { 
    this.setState({query: event.target.value}); 
    console.log('event ' + event.target.value); 
    this.props.history.push('/search'); 
    // history.push('/search') 
    // this.context.router.push('/'); 
    } 

  render() { 
    var query = this.state.query; 
    return (
     <article> 
     <SearchForm query={query} onChange={this.updateInputValue} /> 
     </article> 
    ) 
  } 
} 

感謝您的幫助

回答

0

這可能是因爲當你做this.props.history.push('/search');主頁組件卸除,你失去的狀態。您需要將query存儲在某些外部狀態(如redux)中,或者如果您使用React-Router 4,則還可以使用location state.

相關問題