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

使用react-select-country-list触发React错误#31的原因及修复方案

React-Select 国家选择组件调用save()时出现Minified React Error #31的问题分析与修复

问题原因

  • 初始状态类型不匹配:react-select的value属性要求传入与选项结构一致的对象(如{ label: "China", value: "CN" })或null,但代码中useState("")将citizenship初始化为空字符串,属于无效值,触发React渲染类型错误(对应Minified Error #31)。
  • 空值访问风险:当citizenship为空字符串时,save()函数中访问citizenship.label会抛出Cannot read properties of string (reading 'label')错误,进一步加剧渲染异常。

修复方案

  1. 修正初始状态:将初始值从空字符串改为null,符合react-select的空值规范。
  2. 添加空值校验:在save()中先判断citizenship是否存在,再访问label属性,同时补充async/await的异常处理。
  3. 可选优化:给Select组件添加placeholder属性,明确未选中状态的提示。

修复后的完整代码

import React, { useState, useMemo } from 'react'
import Select from 'react-select'
import countryList from 'react-select-country-list'    

export const Profile = () => {
    // 初始状态改为null,符合react-select的空值要求
    const [citizenship, setCitizenship] = useState(null);

    async function save() {
        // 先校验citizenship是否存在,避免空值访问错误
        if (!citizenship) return;
        
        try {
            await fetch(`${process.env.REACT_APP_SERVER_IP}/api/updateProfile`, {
                headers: { "Content-Type": "application/json" },
                method: "PUT",
                body: JSON.stringify({
                    citizenship: citizenship.label
                }),
            });
            // 可添加保存成功后的逻辑,比如提示用户
        } catch (error) {
            console.error('保存失败:', error);
            // 可添加错误提示逻辑
        }
    }    

    const options = useMemo(() => countryList().getData(), []);

    const changeHandler = (country) => {
        setCitizenship(country)
    }

    return (
        <Select
           options={options}
           value={citizenship}
           onChange={changeHandler}
           placeholder="选择你的国籍" // 可选:添加占位符提示
        />  
    )                       
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 20:43:21