Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - React native fetch data from API and displaying

Hi i'm fairly new to react native and im trying to fetch data from an API, then display them as such in my movies.js . But it gives me the error undefined is not a function(near'..data,map..'). I thought of mapping the json data to an array movieComponent. The console.log(data) shows the data properly as it should in json format. Not sure what i'm doing wrong. Thanks in advance! App.JS

export default function App() {

const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
console.log(data);

useEffect(() => {
    fetch('http://www.omdbapi.com/?s=superman&apikey=28f4dae9')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

const movieComponent = data.map(movie => <Movies key={movie.imdbID} moviee={movie}/> )
console.log(movieComponent);
  return (
<SafeAreaView>
    <ScrollView className="App">
      <Header />
      {movieComponent}
    </ScrollView>
</SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Movies.js

import React from "react"
import { Image , Text , View} from "react-native"

function Movies(props) {
    return (
        <View>
            <Image source={{uri: props.movies.Poster}} 
        style={{width: 300, height: 300}} /> 
            <Text>Title: {props.movies.Title}</Text>
            <Text>Year: {props.movies.Year}</Text>
        </View>
    )
}

export default Movies

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

API response is object { Search: [] } and not an array.

Change from

.then((json) => setData(json))

To

.then((json) => setData(json ? json.Search : []))

Alse issue-2. There is typo moviee={movie}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...