2016-08-16 48 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()'。更新了答案以澄清。 –