我需要在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部分作为参数传递给您的服务。 –