我需要在URL中傳遞動態參數的地方發出請求。首先,我顯示一個商店列表,當用戶點擊一個顯示它的詳細信息時,爲此我使用下面的代碼,但即使嘗試太多,我也無法獲得該ID。帶動態參數的原生反應
類型錯誤:未定義不是一個對象(評價 '_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;
您還沒有向我們展示瞭如何調用'fetchGetById'。你還從服務內部調用'this.props'?道具只能在React組件中使用。您應該將URL部分作爲參數傳遞給您的服務。 –