目标是允许用户在搜索栏中输入关键字,将搜索词或短语存储在字符串中,然后向电影服务器发送发布请求,并以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'
}
});
我的代码有点草率,所以请原谅我,我还是编码的新手。
答案 0 :(得分:0)
问题是您正在componentDidMount
上从API提取数据,但只会被调用一次(安装组件时)。
所以最好的解决方法是
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);
});
}
<Input
placeholder="Type here to translate!"
onChangeText={(text) => {
this.fetchData(text);
}}
/>