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

How do I fetch data from api based on search of the user in React Native?

目标是允许用户在搜索栏中输入关键字,将搜索词或短语存储到字符串中,然后向电影服务器发送 post 请求,并在平面列表格式。

我不擅长 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'
  }
});

我的代码有点马虎所以请原谅我,我还是编码新手。

问题是您在 componentDidMount 上从 API 获取数据,但它只会被调用一次(当组件安装时)。

所以最好的修复方法是

  1. 创建一个名为 fetchData 的函数
  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);
    }}
  />