问题
I am trying to run an expo project, (react-native) but when i run the project, i get following result:
Unable to resolve "fetch" from "src\components\MyScreen\Screen.js"
Fetch should not be a nodejs standard feature? What should i do to run fetch with the project?
Also, if i try to yarn add fetch
, i get a different error.
The package at "node_modules\fetch\lib\fetch.js" attempted to import the Node standard library module "http". It failed because React Native does not include the Node standard library. Read more at https://docs.expo.io/versions/latest/introduction/faq/#can-i-use-nodejs-packages-with-expo
Am i missing something?
Here is where im calling fetch:
fetch(`${API_URL()}/orders`, requestInfo)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Erro ao registrar endereço!");
}
})
.then(currentUser => {
this.setState({ loading: false });
alert("Pedido realizado com sucesso!");
this.props.navigation.navigate("Products");
})
.catch(error => {
this.setState({ loading: false });
alert(error.message);
});
回答1:
According to Expo doc you don't need to import anything. Just use fetch
in the code.
import React from 'react'; import { FlatList, ActivityIndicator, Text, View } from 'react-native'; export default class FetchExample extends React.Component { constructor(props) { super(props); this.state = { isLoading: true }; } componentDidMount() { return fetch('https://facebook.github.io/react-native/movies.json') .then(response => response.json()) .then(responseJson => { this.setState( { isLoading: false, dataSource: responseJson.movies, }, function() {} ); }) .catch(error => { console.error(error); }); } render() { return ( .... ); } }
来源:https://stackoverflow.com/questions/60837915/expo-unable-to-resolve-fetch