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

React Native中如何为Picker组件设置API返回的选项值?

修复方案

你代码存在多处语法和逻辑错误,对应修正点如下:

  • 自定义方法getdata未绑定this指向,调用setState时会抛出异常,改为箭头函数即可修正
  • 废弃生命周期componentWillMount替换为标准的componentDidMount用于发起接口请求
  • 删除错误导入的React Native内部PickerItem,@react-native-picker/picker自带的Picker.Item可直接使用
  • 修复Picker标签多余的}语法错误
  • 核心逻辑补全:遍历state.stateList动态渲染Picker.Item组件,这是数据不显示的核心原因
  • 新增selectedValue状态字段存储当前选中的Picker值,修正onValueChange的回调逻辑
  • 移除固定选项中错误的字符串硬编码,使用JSX表达式{}读取状态变量

修正后的完整代码如下:

import React, { Component } from "react";
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import { Picker } from "@react-native-picker/picker";

// 基础样式补全,可根据需求自行调整
const styles = StyleSheet.create({
  TouchableOpacity: {
    backgroundColor: '#2196F3',
    padding: 10,
    borderRadius: 4,
    marginTop: 16,
    alignItems: 'center'
  }
})

class VolunteerPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stateList: [],
            selectedValue: '' // 存储Picker当前选中值
        };
    }

    componentDidMount() {
        this.getdata();
    }

    // 改为箭头函数修正this指向
    getdata = () => {
        var temp = [];
        // 替换为实际的接口地址
        const url = "https://www.example.com";

        fetch(url, {
            method: 'POST',
            headers: new Headers({'Content-Type': 'application/json'})
        })
        .then(res => res.json())
        .then((response) => {
            console.log("Response : ",response);
            var length = response.state?.length || 0;
            console.log("Length of State is : ",length);
            if (length > 0) {
                for (let i = 0; i < length; i++) {
                    var data = response.state[i];
                    var joined = { value: data.amd_state };
                    temp.push(joined);
                }
            }
            this.setState({
                stateList: temp
            });
        })
        .catch(error => console.error('Error : ', error))
    }

    apiCallHere = () => {
        // 后续业务逻辑,可通过this.state.selectedValue拿到当前选中的项
        console.log('选中的值:', this.state.selectedValue)
    }

    render() {
        return (
            <View style={{padding: 16}}>
                <Picker
                  selectedValue={this.state.selectedValue}
                  onValueChange={(itemValue)=> this.setState({selectedValue: itemValue})}
                >
                    <Picker.Item label="请选择省份" value="" />
                    {/* 遍历stateList动态生成选项 */}
                    {
                      this.state.stateList.map((item, index) => (
                        <Picker.Item 
                          key={index} 
                          label={item.value} 
                          value={item.value} 
                        />
                      ))
                    }
                </Picker>

                <TouchableOpacity style={styles.TouchableOpacity} onPress={this.apiCallHere}>
                    <Text style={{ color: "white" }}>下一步</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

export default VolunteerPage

如果运行后仍无数据,可先确认接口返回的response.state数组中,每一项确实存在amd_state字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:36:00