React-native Fetch with dynamic params

时间:2017-11-17 21:27:22

标签: reactjs react-native react-router react-redux

我需要在URL中传递动态参数。首先我显示商店列表,当用户点击我显示它的详细信息时,为此我使用下面的代码,但即使尝试了太多,我也无法获得ID。

TypeError:undefined不是对象(评估' _this.props.navigation')

这是我的服务:



import api from '../../../config/api';

export const fetchGetById = () => {
  return (
    fetch(`${api.API_URL}stores/v1/getById?id=${this.props.navigation.state.params.id}`, {
      method: 'get',
      headers: {
        mall: api.API_MALL,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    })
      .then(res => res.json())
      .then(data => data.result.store)
      .catch(err => err)
  );
}

export default fetchGetById;




这是我的组件,ID:{this.props.navigation.state.params.id}我正确地得到了params.id:



import React, { Component } from 'react';
import {
  View,
  Text,
  ActivityIndicator,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Styles from './view-component-styles';
import Theme from '../../../config/theme';

type Props = {
  error: boolean,
  loading: boolean,
  data: Object,
  fetchData: Function,
};

class ViewComponent extends Component<Props> {

  constructor() {
    super();
    this.goToPage = this.goToPage.bind(this);
  }

  componentDidMount() {
    this.props.fetchData();
  }

  goToPage(param, id) {
    this.props.navigation.navigate(param, { id: id });
  }

  render() {
    const hasData = Object.keys(this.props.data).length;

    const errorMessage = () => {
      return (
        <Text>Ops! Ocorreu um erro ao carregar os dados.</Text>
      );
    };

    const renderLoading = () => {
      return (
        <View style={Styles.renderLoading}>
          <ActivityIndicator color={Theme.color.secondary} size="large" />
          <Text style={Theme.text}>Aguarde</Text>
        </View>
      );
    };

    const getData = (data) => {
      return (
        <View>
          <Text>ID: { this.props.navigation.state.params.id }</Text>
          <Text>{ data.fantasy_name }</Text>
        </View>
      );
    };

    return (
      <View style={Styles.container}>
        { this.props.loading ? renderLoading() : null }
        { this.props.error ? errorMessage() : null }
        { hasData ? getData(this.props.data) : null }
      </View>
    );
  }
}

export default ViewComponent;
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以尝试使用

export const fetchGetById = ( myid ) => {
  return (
    fetch(`${api.API_URL}stores/v1/getById?id=myid`, {
      method: 'get',
      headers: {
        mall: api.API_MALL,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    })
      .then(res => res.json())
      .then(data => data.result.store)
      .catch(err => err)
  );
}