从服务器(REST API)获取数据并在React Native中的多选选择器中设置数据

时间:2019-06-17 07:04:03

标签: javascript reactjs react-native

我正在使用REST API从服务器中获取数据,我想在React Native中的多选选择器中设置该数据,但出现错误。这是服务器发出的我的回复:

[
  {
    "id": 22,
    "name": "Business",
    "slug": "business"
  },
  {
    "id": 17,
    "name": "Digital Marketing",
    "slug": "digital-marketing"
  },
  {
    "id": 23,
    "name": "Fun & Lifestyle",
    "slug": "fun-lifestyle"
  },
  {
    "id": 16,
    "name": "Mobiles",
    "slug": "mobiles"
  }]

我想在下拉菜单中设置名称,然后从中选择多个值。这是我的代码:

import React from 'react';
import { View, StyleSheet } from 'react-native';
import MultiSelect from 'react-native-multiple-select';

export default class PostJob extends React.Component {
  state = {
     LangPickerValueHolder: [],
    LangKnown: []
  }

  componentDidMount () {
    fetch('taxonomies/get_taxonomy?taxonomy=project_cat').then(response => response.json())
        .then(responseJson => {
          let langString = responseJson;

          let LangPickerValueHolder = langString.map((name, id) => { return { name, id }; });
          this.setState({
            LangPickerValueHolder
          });
          console.log(langArray);
        }).catch(error => {
          console.error(error);
        });
  }

  render () {
    return (
      <View style={styles.container}>
        <MultiSelect
          ref={(component) => { this.multiSelect = component; }}
          onSelectedItemsChange={(value) =>
            this.setState({ LangKnown: value })
          }
          uniqueKey="id"
          items={this.state.langString}
          selectedItems={this.state.LangKnown}
          onChangeInput={ (text) => console.log(text)}
          displayKey = 'name'
          submitButtonText="Submit" />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: 'white',
    padding: 8
  }
});

但是它没有显示任何项目。

2 个答案:

答案 0 :(得分:0)

您的商品似乎应该引用LangPickerValueHolder而不是langString

 <View style={styles.container}>
    <MultiSelect
      ref={(component) => { this.multiSelect = component; }}
      onSelectedItemsChange={(value) =>
        this.setState({ LangKnown: value })
      }
      uniqueKey="id"
      items={LangPickerValueHolder}
      selectedItems={this.state.LangKnown}
      onChangeInput={ (text) => console.log(text)}
      displayKey = 'name'
      submitButtonText="Submit" />
  </View>

答案 1 :(得分:0)

  1. 您的映射错误。应该是langString.map(item => ({ name: item.name, id: item.id }))
  2. items道具应该是this.state.LangPickerValueHolder