下拉菜单,反应路由器和返回按钮
问题描述:
当您从下拉列表中选择某个内容时,这个小组件会更改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}`)
}
}
答
你的问题是,你正在使用状态来管理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}`)
}
}
真棒!如果在之下有'
{this.getSelected()}
'会怎么样?如何使其工作,使getSelected()不会运行2次? – Solo将输出添加到变量,并将其传递给'Dropdown':'const selected = this.getSelected()'。更新了答案以澄清。 –