简体   繁体   English

我如何在 React-Native 上使用 API 和 axios

[英]How can i use API with axios on React-Native

i am a student and i began to develop mobile application about books.我是一名学生,我开始开发有关书籍的移动应用程序。 I am trying to get random books list with use axios and api.我正在尝试使用 axios 和 api 获取随机书籍列表。 I am beginner in React-Native so i tried to find how can I use but many tutorial videos use components for create an app.I use functions.我是 React-Native 的初学者,所以我试图找到如何使用,但许多教程视频使用组件来创建应用程序。我使用函数。 I found some codes for help me but this codes belongs to React.js.我找到了一些帮助我的代码,但这些代码属于 React.js。 I couldnt convert to React-Native.我无法转换为 React-Native。 Here are the codes.这是代码。

import React, { useState } from 'react';
import {View,Text,Button,StyleSheet,TextInput,TouchableOpacity} from 'react-native';

import Axios from 'axios';



const ExploreScreen = () => {
    const [book,setBook] = useState("");
        const [result,setResult] = useState([]);
        const [apiKey,setApiKey] = useState("AIzaSyBW3SP0vixN1EX8VueI9VL5wzbbjTm")

    function handleChange(event){
        const book =event.target.value;
        setBook(book);
    }

    function handleSubmit(event){
        event.preventDefault();
        
        axios.get("https://www.googleapis.com/books/v1/volumes?q="+book+"&key="+apiKey+"&maxResults=40")
        .then(data => {
            console.log(data.data.items);
            setResult(data.data.items)
        })
    }

    return (
        <View style={StyleSheet.contianer}>
            <TextInput
            onChangeText={() => handleChange()}></TextInput>
            <TouchableOpacity
                title="Click here"
                onPress={() => handleSubmit()}/>
            {result.map(book =>(
                <a target="_blank" href={book.volumeInfo.previewLink}>
                <Image src={book.volumeInfo.imageLinks.thumbnail} alt={bookTitle}
                />
                </a>
            ))}
        </View>
    );
};
export default ExploreScreen;

const styles=StyleSheet.create({
    contianer: {
        flex:1,
        alignItems:'center',
        justifyContent:'center'
    }
}) 

I haven't watched it closely, but the error you are referring:我没有仔细观察它,但是您所指的错误是:

undefined is not an object evualating.event.target undefined 不是 object evalating.event.target

is because both onChangeText and onPress have no arguments, thus event is undefined when the function is called.是因为onChangeTextonPress都没有 arguments,因此在调用 function 时事件未定义。

You should instead pass the event as an argument, for example:您应该将事件作为参数传递,例如:

onChangeText={event => handleChange(event)}

You can find an example of both components with examples on the documentation: https://reactnative.dev/docs/textinput您可以在文档中找到两个组件的示例和示例: https://reactnative.dev/docs/textinput

https://reactnative.dev/docs/touchableopacity https://reactnative.dev/docs/touchableopacity

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM