使用bootstrap-select的下拉组件按返回键后不展示国家列表如何解决
问题原因
bootstrap-select是基于jQuery实现的插件,初始化时会将原生的<select>节点替换为自定义的DOM结构来实现样式和交互效果。后续React更新原生<select>下的<option>节点时,bootstrap-select生成的自定义下拉列表不会自动同步变更- 路由跳转回退时,当前组件重新渲染生成了新的原生
<select>和<option>节点,但你没有重新触发bootstrap-select的初始化/刷新逻辑,导致自定义下拉列表没有加载最新的option内容
解决方案
- 给
<select>节点绑定Ref,方便后续调用bootstrap-select的内置方法 - 在组件挂载生命周期初始化下拉组件,组件更新时手动触发刷新,组件卸载时销毁实例避免内存泄漏
- 建议将
country-list的getNames()返回结果存入组件state,避免渲染时重复执行方法
修改后的代码示例
首先构造函数内初始化Ref和state:
import { getNames } from 'country-list'; class YourComponent extends React.Component { constructor(props) { super(props); this.selectRef = React.createRef(); this.state = { countries: [] }; } componentDidMount() { // 挂载时先获取国家列表存入state this.setState({ countries: getNames() }, () => { // state更新完成后初始化bootstrap-select $(this.selectRef.current).selectpicker(); }); } componentDidUpdate() { // 组件更新时刷新下拉列表,同步最新的option内容 $(this.selectRef.current).selectpicker('refresh'); } componentWillUnmount() { // 卸载时销毁组件实例 $(this.selectRef.current).selectpicker('destroy'); } handleLocation = (e) => { // 你的原有逻辑 } render() { return ( <select ref={this.selectRef} onChange={this.handleLocation} data-live-search="true" className="selectpicker" data-selected-text-format="count" data-size="7" title="Select Country" > {this.state.countries.map((e) => { return <option key={e} value={e}>{e}</option> })} </select> ) } }
注意事项
- 确保你项目中已经正确引入了jQuery、bootstrap的CSS/JS、bootstrap-select的CSS/JS依赖,依赖顺序不能乱:先引入jQuery,再引入bootstrap的JS,最后引入bootstrap-select的JS
- 如果你的项目用的是函数组件,可以用useRef、useEffect钩子实现对应生命周期的逻辑
内容的提问来源于stack exchange,提问作者abdul riyaz
相关产品推荐
相关产品推荐

