目标是允许用户将关键字输入搜索栏中,将搜索单词或短语存储到字符串中,然后将帖子请求发送到电影服务器并显示结果采用扁平列表格式。
我不熟练使用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的数据,但仅将其调用一次(当组件安装时)。
因此,修复它的最佳方法是
- 创建一个称为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);
});
}
- 在OnchangeText中,致电FetchData
<Input
placeholder="Type here to translate!"
onChangeText={(text) => {
this.fetchData(text);
}}
/>