2016-08-16 71 views
0

當您從下拉列表中選擇某個內容時,這個小組件會更改URL。一切工作正常..除了後退按鈕。如果按下它,其他所有內容都會更改,但下拉列表不會更改。下拉菜單,反應路由器和返回按鈕

究竟如何?

  • 如果我去的着陸頁,默認值是所有
  • 現在我選擇
  • 現在
  • 再次
  • 最後
  • 立即,如果我點擊後退按鈕,下拉菜單總是顯示最後一次選擇的值(在我的例子)

如何解決這個問題?


class MyComponent extends React.Component { 

    constructor (props) { 
     super(props) 
     this.state = { 
      selected: { 
       // This only affects dropdown if landing to page 
       value: this.props.params.color, // Get param from url 
       label: // Some irrelevant uppercase magic here 
      } 
     } 
    } 

    static defaultProps = { 
     colors: [ 
      {value: 'all', label: 'All'}, 
      {value: 'red', label: 'Red'}, 
      {value: 'blue', label: 'Blue'} 
     ] 
    } 

    render() { 
     return ( 
      <Dropdown 
       options={this.props.colors} {/* All options */} 
       value={this.props.selected} {/* Selected option */} 
       onChange={this.handleSelect.bind(this)} 
      /> 
     ) 
    } 

    handleSelect(color) { 
     this.setState({selected: color}) 
     browserHistory.push(`/${color.value}`) 
    } 
} 

回答

2

你的問題是,你正在使用狀態來管理selected道具你Dropdown組件,然而,當你瀏覽前進/後退路由器不更新此。

而是從組件完全刪除狀態,並使用路由器來直接檢測selected項目:

import { find } from 'lodash'; 

class MyComponent extends React.Component { 

    static defaultProps = { 
     colors: [ 
      {value: 'all', label: 'All'}, 
      {value: 'red', label: 'Red'}, 
      {value: 'blue', label: 'Blue'} 
     ] 
    } 

    getSelected() { 
     const colours = this.props.colours 
     const selectedColour = this.props.params.colour 

     // Find the option matching the route param, or 
     // return a default value when the colour is not found 
     return find(colours, { value: selectedColour }) || colours[0]; 
    } 

    render() { 
     const selectedOption = this.getSelected(); 
     return (
      <div> 
       <Dropdown 
        options={ this.props.colors } {/* All options */} 
        value={ selectedOption } {/* Selected option */} 
        onChange={ this.handleSelect.bind(this) } 
       /> 
       <p>You selected: { selectedOption.label }</p> 
      </div> 
     ) 
    } 

    handleSelect(color) { 
     browserHistory.push(`/${color.value}`) 
    } 
} 
+0

真棒!如果在之下有'

{this.getSelected()}

'會怎麼樣?如何使其工作,使getSelected()不會運行2次? – Solo

+0

將輸出添加到變量,並將其傳遞給'Dropdown':'const selected = this.getSelected()'。更新了答案以澄清。 –