0

我想将 Django Rest Framework 中的数据显示到 DropDownPicker React-Native ( https://github.com/hossein-zare/react-native-dropdown-picker ) 这是我的代码:

import React, { useState, useEffect } from "react";
import { StyleSheet, View, Text, Image, FlatList, Button, TouchableOpacity } from "react-native";
import client from "./../../api/client";
import DropDownPicker from 'react-native-dropdown-picker';


const Droplo = ({navigation, route}) => {
  const [detailha, setDetailha] = useState("");
  const [value, setValue] = useState(null);
  let controller;

  const getDetailha = async (url) => {
    try {
      const response = await client.get(url);
      if (!response.ok) {
        setDetailha(response.data);
        console.log(response.data)
      }
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(()=>{ getDetailha('/habilidad/'); }, [])

  return (
      <View>
        <DropDownPicker
            items={detailha}
            controller={instance => controller = instance}
            onChangeList={(items, callback) => {
                new Promise((resolve, reject) => resolve(setDetailha(items)))
                    .then(() => callback())
                    .catch(() => {});
            }}
            defaultValue={value}
            onChangeItem={item => setValue(item.nombre_habilidad)}
        />
      </View>
    );
  }

export default Droplo;

数据是:

在此处输入图像描述

错误是:

在此处输入图像描述

谢谢你!

4

1 回答 1

0

您的数据格式不正确。

请参阅本段:https ://github.com/hossein-zare/react-native-dropdown-picker#single-item

道具的item格式应该是这样的:

[
  { label: 'item-label', value: 'item-value', icon: () => <span>your-icon</span> }, 
  ... 
]

因此,您可以更改服务器的响应或从响应数据中创建一个新数组并传递itemprop。

responseData.map(elem => ({label: elem.nombre_habilidad, value: elem.nombre_habilidad})

你也应该改变 state 的初始值detailha,因为itemprop 需要array类型。(在获取 API 之前,react-native-dropdown-picker组件将使用初始值呈现)您可以使用空数组进行初始化:

const [detailha, setDetailha] = useState([]);

此更改将修复您提供的错误

于 2021-03-18T03:26:21.460 回答