下拉菜单,React Router和back按钮



当您从下拉菜单中选择内容时,这个小组件会更改URL。一切正常…除了返回按钮。如果我按下它,其他的都会改变,但下拉菜单不会改变。

如何?

  • 如果我进入着陆页面,默认值是All
  • 现在我选择红色蓝色现在
  • 红再次
  • 蓝色
  • 最后
  • 现在,如果我点击后退按钮,下拉菜单总是显示最后选择的值(在我的例子中是蓝色)

如何克服这个问题?


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}`)
    }
}

您的问题是您正在使用状态来管理Dropdown组件的selected prop,但是当您向后/向前导航时,路由器不会更新此状态。

相反,从你的组件中完全删除状态,并使用路由器直接检测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}`)
    }
}

最新更新