【问题标题】:Not showing data fetched from api ( React Native )不显示从 api ( React Native ) 获取的数据
【发布时间】:2019-11-30 04:52:02
【问题描述】:

我想显示从 DropdownModal (https://github.com/sohobloo/react-native-modal-dropdown) 中的 API 获取的数据列表。数据是用户地址,包括姓名、州、国家和所有与地址相关的内容。但它不会显示在下拉列表中,它会显示加载图标,这意味着它是 null 或 undefined 。但是我确实从 API 中获取了数据,我通过对错误和结果发出警报来验证这些数据(是的,它们都给出了相同的数据,即地址)。 下面是我的代码。

const {getAddresses} = auth;
var {width, height} = Dimensions.get('window');

class RegisterEventOne extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      event_id: '',
      tshirt_size: '',
      size: '',
      address: '',
      addressx: '',
     };
    this.onResult = this.onResult.bind(this);
    this.onError = this.onError.bind(this);

  }

  handleWithDropdownCategory = id => {
    this.setState({event_id: id});
  };

  handleWithDropdownSize = size => {
    this.setState({tshirt_size: size});
  };

  TShirtSize = size => {
    this.setState({size: size});
  };

  setAddress = address => {
    this.setState({addressx: address})
  }

  componentDidMount() {
    this.props.getAddresses(this.props.event.id, this.onResult, this.onError);

  }

  onError(error) {
    alert(JSON.stringify(error));

  }

  onResult(result) {
    this.setState({
      address: result,
    });
  }

  render() {
    return (
      <React.Fragment>
        <StatusBar backgroundColor="black" barStyle="light-content" />
        <SafeAreaView style={styles.container}>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            style={styles.scrollView}>
            <View>
              <Text style={styles.eventname}>{this.props.event.name}</Text>
              <ModalDropdown
                dropdownStyle={styles.dropdown}
                dropdownTextStyle={{fontSize:15}}
                style={styles.dropdown}
                onSelect={(index, value) => {
                  this.handleWithDropdownCategory(value);
                }}

                options={this.props.event.categories.map(function(event) {
                  return event.name;
                })}>
                <View style={styles.dropdowncontainer}>
                  <Text>{this.state.event_id === '' ? 'Select Category' : this.state.event_id}</Text>
                  <Ionicons name="ios-arrow-down" size={20} color="black" />
                </View>
              </ModalDropdown>
              <ModalDropdown
                dropdownStyle={styles.dropdown}
                dropdownTextStyle={{fontSize:15}}
                style={styles.dropdown}
                onSelect={(index, value) => {
                  this.handleWithDropdownSize(value);
                  this.TShirtSize(index+1);
                }}
                options={this.props.event.tshirts.map(function(event, index) {
                  return event.size;
                })}
                >
                <View style={styles.dropdowncontainer}>
              <Text>{this.state.tshirt_size === '' ? 'Select Tshirt Size' : this.state.tshirt_size}</Text>
                  <Ionicons name="ios-arrow-down" size={20} color="black" />
                </View>
              </ModalDropdown>
              <ModalDropdown
                dropdownStyle={styles.dropdown}
                style={styles.dropdown}
                dropdownTextStyle={{fontSize:15}}
                onSelect={(index, value) => {
                this.setAddress(value);
                }}

                options={this.state.address !== '' ? this.state.address.map(function(address, index)  {
                  return address.id;
                }):null}

                >

                <View style={styles.dropdowncontainer}>
              <Text>{this.state.addressx === '' ? 'Select Address' : this.state.addressx}</Text>
                  <Ionicons name="ios-arrow-down" size={20} color="black" />
                </View>
              </ModalDropdown>

              {/* <Text style={styles.header}>Compete with ohters (Optional)</Text>
              <TextInput
                style={styles.header}
                onChangeText={text => onChangeText(text)}
                placeholder="Set Date & Time (Time zone)"
              /> */}
              {/* <View style={styles.checkboxcontainer}>
                <BouncyCheckbox
                  textColor="#000"
                  fillColor="orange"
                  fontFamily="JosefinSans-Regular"
                  text="Individual Competition"
                />
                <BouncyCheckbox
                  textColor="#000"
                  fillColor="orange"
                  fontFamily="JosefinSans-Regular"
                  text="Team Competition"
                />
                <TextInput
                  style={styles.header}
                  onChangeText={text => onChangeText(text)}
                  placeholder="Team member limit"
                />
                <TextInput
                  style={styles.header}
                  onChangeText={text => onChangeText(text)}
                  placeholder="Username / Email"
                />
                <TextInput
                  style={styles.header}
                  onChangeText={text => onChangeText(text)}
                  placeholder="Username / Email"
                />
                <TextInput
                  style={styles.header}
                  onChangeText={text => onChangeText(text)}
                  placeholder="Username / Email"
                />
              </View> */}
            </View>
          </ScrollView>
          <View style={styles.processIndicator}>
            <TouchableOpacity disabled>
              <Text style={styles.textProcessPrimary}>Previous</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={()=>Actions.RegisterEventThree({event_id: this.props.event.categories[0].event_id, category_id: this.state.event_id, size: this.state.size, address: this.state.addressx})}>
              <Text style={styles.textProcessPrimary}>Next</Text>
            </TouchableOpacity>

          </View>
        </SafeAreaView>
      </React.Fragment>
    );
  }
}

export default connect(
  null,
  {getAddresses},
)(RegisterEventOne);

API:

    export function getAddresses(data, callback) {
  AsyncStorage.getItem('token').then(value => {
    const token = JSON.parse(value);
    fetch('https:apiurl.com', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: 'bearer' + token.access_token,
      },

    })
    .then(response => response.json())
    .then(response => callback(response.data))
    .catch(error => callback(false, null, error.json()));

【问题讨论】:

    标签: api react-native


    【解决方案1】:

    仅当数据(选项)为undefinednull 时才会显示加载指示器。这意味着您根本没有数据,或者数据结构不好。

    您说过错误警报也会被触发,这并不是一件好事。我不知道为什么错误会向您显示一些数据。 (错误数据除外)。

    选项应该以这种格式传递:['data1', 'data2']

    另外,您从 redux => this.props.event.categories 而不是 state 中获取数据。如果你想使用 redux,那么你在connect fnc 中缺少某种mapStateToProps

    这段代码中有很多错误的模式。查看一些有关如何使用 redux 的示例,如果您想使用它,还可以查看 react-native-modal-dropdown github repo 中的示例。

    【讨论】:

    • 其实这段代码不是我写的。它是由我团队中的其他人编码的,他没有回复我的消息,所以你可以说我并不真正理解所有代码,但我至少必须在星期一之前完成这个。我也不知道为什么错误给了我数据。错误和结果都给了我相同的输出,即数据。对于选项,T 恤尺寸和类别确实显示在下拉列表中,但地址没有。我将看看如何使用 redux 来更好地理解。感谢您的建议。
    【解决方案2】:

    现在解决了。 我刚刚在 response.data 后面添加了 ,true,null 。 它看起来像这样: .then(response => 回调(response.data,true,null)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-02
      • 2021-09-26
      • 2021-12-23
      • 1970-01-01
      • 2021-10-19
      • 2021-10-16
      • 2017-09-05
      • 2019-05-08
      相关资源
      最近更新 更多