2016-08-16 8 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

あなたの問題は、あなたが/前方に戻って移動するときただし、ルータがこれを更新しない、あなたのDropdownコンポーネントのselected小道具を管理するために、状態を使用していることです。

代わりにあなたのコンポーネントから完全な状態を削除し、直接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

出力を変数に追加し、代わりに 'Drop selected'に渡します:' const selected = this.getSelected() '。明確にするための答えを更新しました。 –