You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React实现GraphQL数据源select选中值存入localStorage

Select下拉选中值localStorage持久化实现方案

核心改动分为4个部分,直接替换原有组件代码即可:

  • 初始化组件状态时优先读取localStorage缓存的选中值,无缓存时等接口返回后自动设置默认选中项
  • 给select标签绑定受控value与onChange事件,实现选中值双向绑定
  • 遍历生成option时补充唯一value与key属性,移除option内部非法的div嵌套(option内仅支持文本内容,样式直接加在option标签上)
  • 监听选中变化事件,选中项更新时同步写入localStorage完成持久化

修改后完整代码:

const Currency_Query = gql`
{
    currencies{
      label
      symbol
    }
  }
`;

class Currency extends Component {
  constructor(props){
    super(props);
    this.state = {
      currencies: [],
      // 初始化时优先读取本地缓存
      selectedCurrency: localStorage.getItem('selected_currency') || ''
    }
  }

  // 选中项变化处理逻辑
  handleCurrencyChange = (e) => {
    const newSelected = e.target.value;
    this.setState({
      selectedCurrency: newSelected
    });
    // 写入本地存储完成持久化
    localStorage.setItem('selected_currency', newSelected);
  }
    
  componentDidMount = async () =>{
    const response = await client.query({
      query: Currency_Query
    })
    const currencies = response.data.currencies;
    this.setState({
      currencies: currencies
    })
    // 本地无缓存时,默认选中第一个选项
    if (!this.state.selectedCurrency && currencies.length > 0) {
      const defaultVal = currencies[0].label;
      this.setState({
        selectedCurrency: defaultVal
      })
      localStorage.setItem('selected_currency', defaultVal);
    }
  }
    
  render() {
    return(
        <div className={s.select}>
           <select 
            value={this.state.selectedCurrency}
            onChange={this.handleCurrencyChange}
           >
          {this.state.currencies.map((currency) =>(
              <option 
                key={currency.label}
                value={currency.label}
                className={s.option}
              >
                  {currency.symbol} {currency.label}
              </option>
              )
            ) 
          }
            </select> 
        </div>
        );
    }
}

export default Currency;

补充说明:如果业务中货币label可能重复,可以把option的value换成symbol或者接口返回的唯一id字段,保证选中值能匹配唯一选项即可,localStorage中存储的键名也可以根据业务需要自行修改。

内容的提问来源于stack exchange,提问作者Nord

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 17:30:50