我想实现某种方法中的搜索逻辑,然后将其传递给TextInput道具'onChangeText'。我想我应该遍历数组“ popularMovies”,并确定我的输入值是否与特定标题匹配。问题是我不确定应该如何看。 预先谢谢你!
import React, { Component } from 'react';
import { FlatList, View, StatusBar, TextInput } from 'react-native';
import { bindActionCreators } from 'redux';
import type { Dispatch as ReduxDispatch } from 'redux';
import { connect } from 'react-redux';
import { fetchPopularMovies } from '../../actions/PopularMovieActions';
import addToFavourite from '../../actions/FavouriteMovieActions';
import MovieCard from '../../components/movieCard/MovieCard';
type Props = {
fetchPopularMovies: Function,
popularMovies: Object,
navigation: Object,
}
class ListOfPopularContainer extends Component<Props> {
state = {
refreshing: false,
text: '',
}
componentDidMount() {
this.props.fetchPopularMovies();
}
search(text) {
this.setState({ text });
// SEARCH LOGIC SHOULD GO HERE
}
onRefresh() {
this.setState({ refreshing: true });
this.props.fetchPopularMovies();
this.setState({ refreshing: false });
}
render() {
const { popularMovies, navigation } = this.props;
return (
<View>
<TextInput
placeholder="Search movie"
onChangeText={ (text) => this.search(text) }
value={this.state.text}
/>
<StatusBar
translucent
backgroundColor="transparent"
barStyle="light-content"
/>
<FlatList
onRefresh={() => this.onRefresh()}
refreshing={this.state.refreshing}
data={popularMovies}
keyExtractor={item => item.title}
renderItem={({ item }) => (
<MovieCard
addToFavourite={() => this.props.addToFavourite(item)}
navigation={navigation}
card={item}
/>
)}
/>
</View>
);
}
}
const mapStateToProps = state => ({
popularMovies: state.popularMovies.popularMovies,
});
const mapDispatchToProps = (dispatch: ReduxDispatch): Function => (
bindActionCreators({ fetchPopularMovies, addToFavourite }, dispatch)
);
export default connect(mapStateToProps, mapDispatchToProps)(ListOfPopularContainer);
答案 0 :(得分:0)
我不确定您要问什么,您的设置正确,看起来不错。您是否想知道如何过滤流行电影?这将是使用香草JS实现它的一种方式。
search(text) {
this.setState({ text });
// SEARCH LOGIC SHOULD GO HERE
let searchedMovies = this.state.popularMovies.filter(ele =>
ele.title.includes(text))
this.setState({searchedMovies})
}
答案 1 :(得分:0)
您应该查看lodash。特别是两个功能:
包含
https://lodash.com/docs/4.17.10#includes
此函数检查一个字符串是否包含在另一个字符串中。
import { includes } from 'lodash';
search(text) {
var searchResults = [];
var { popularMovies } = this.props;
for (var i = popularMovies.length -1; i >= 0; i--) {
includes(popularMovies[i], text) && searchResults.push(popularMovies[i])
}
return searchResults;
}
反跳
https://lodash.com/docs/4.17.10#debounce
此功能可限制某个功能,以便用户在键入时会以合理的间隔定期搜索该词组
debounce(search(text))