如何根据在React Native中搜索用户从api获取数据?

问题描述 投票:1回答:1

目标是允许用户将关键字输入到搜索栏中,将搜索词或短语存储到字符串中并将发布请求发送到电影服务器并以FlatList格式显示结果。

我不熟悉javascript,但到目前为止我能够将搜索输入存储到变量中并通过控制台记录搜索确认它,但使用该变量来渲染并显示结果令人困惑

import React, { Component } from "react";
import { 
    View,
    Text,
    FlatList,
StyleSheet
} from "react-native";
import { Container, Header,Item,Input, Left, Body, Right, Button, Icon, 
 Title } from 'native-base';




class Search extends Component {
    constructor(props) {
       super(props);
        this.state = {text: ''};
        this.state = {
         dataSource: []
        }
      }
  renderItem = ({item}) => {

    return (

       <Text>{item.title}</Text>

)}

componentDidMount() {
    const apikey = "&apikey=thewdb"
    const url = "http://www.omdbapi.com/?s="
    fetch(url + this.state.text + url)
    .then((response) => response.json())
    .then((responseJson)=> {
        this.setState({
            dataSource: responseJson.Search

        })
    })
    .catch((error) => {
        console.log(error)
    })


}


render() {
    return (
        <Container>
            <Header
                searchBar rounded
            >
                <Item>
                    <Icon name="ios-search" />
                    <Input 
                        placeholder="Type here to translate!"
                        onChangeText={(text) => this.setState({text})}
                    />
                </Item>
                <Button
                transparent
                onPress={()=> {
                        {console.log(this.state.text)}
                        }
                    }
                >
                    <Text>Search</Text>
                </Button>
            </Header>
            <FlatList
                style={{flex: 1, width:300}}
                data={this.state.dataSource}
                keyExtractor={(item, index) => 'key'+index}
                renderItem={this.renderItem}
                />
        </Container>
         );
     }
}

export default Search;

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

我的代码有点草率所以请原谅我,我还是新编码。

react-native react-native-android react-navigation react-native-ios native-base
1个回答
0
投票

问题是你从componentDidMount上的API获取数据,但它只会被调用一次(当组件被挂载时)。

所以解决它的最佳方法是

  1. 创建一个名为fetchData的func
  fetchData(text) {
    this.setState({ text });
    const apikey = '&apikey=thewdb';
    const url = 'http://www.omdbapi.com/?s=';
    fetch(url + text + url)
      .then(response => response.json())
      .then((responseJson) => {
        this.setState({
          dataSource: responseJson.Search,
        });
      })
      .catch((error) => {
        console.log(error);
      });
  }
  1. 在onChangeText中,调用fetchData
  <Input
    placeholder="Type here to translate!"
    onChangeText={(text) => {
      this.fetchData(text);
    }}
  />
© www.soinside.com 2019 - 2024. All rights reserved.