index.js 2.69 KB
import Taro, { Component } from '@tarojs/taro';
import { View, Text} from '@tarojs/components';
import { SearchItem, SearchBar, PageTitle } from '../../components';
import {search as searchModel} from '../../models';
import './index.scss';
import router from '../../router/index';

export default class Search extends Component {
	constructor() {
		super(...arguments);
		this.state = {
			hotSearch: [],
			latelySearch: [],
			hotSearchTitle: '热门推荐',
			latelySearchTitle: '最近搜索',
			fixed: false
		};
	}

	config = {
		navigationBarTitleText: '搜索'
	}

	componentDidMount () {
		const list = Taro.getStorageSync('latelySearch');
		console.log(list);
		this.setState({
			latelySearch: list || []
		})
		searchModel.getSearchWord().then(ret => {
			if (ret && ret.code === 200) {
				this.setState({
					hotSearch: ret.data || []
				});
			}
		})
	}

	componentDidShow() {
		const list = Taro.getStorageSync('latelySearch');
		this.setState({
			latelySearch: list || []
		})

	}

	onScroll(e) {
		if (e.detail.scrollTop > 48) {
			this.setState({
				fixed: true
			});
		} else {
			this.setState({
				fixed: false
			});
		}
	}

	onScrolltoupper() {
		this.setState({
			fixed: false
		});
	}

	onComplate(e) {
		if (e.detail.value === '') {
			return;
		}
		this.savaLateSearch(e);	
		router.go('productList', {
				query: e.detail.value
		});
	}

	savaLateSearch(e) {
		const latelySearch = this.state.latelySearch;
		if (latelySearch.length >= 10) {
			latelySearch.pop();
		}
		latelySearch.unshift({search_word: e.detail.value});
		try {
			Taro.setStorageSync('latelySearch', latelySearch);
		} catch (error) {
			console.log(error);
		}
		this.setState({
			latelySearch
		})
	}

	onRemoveAllSearch() {
		try {
			Taro.setStorageSync('latelySearch', []);
		} catch (error) {
			console.log(error);
		}
		this.setState({
			latelySearch: []
		})
	}

	render () {
		let {hotSearchTitle, hotSearch, latelySearchTitle, latelySearch} = this.state;
		let value = '';

		return (
			<ScrollView
				className='search-page'
				scrollY
				scrollWithAnimation
				scrollTop='0'
				lowerThreshold='20'
				upperThreshold='20'
				onScrolltoupper={this.onScrolltoupper}
				onScroll={this.onScroll}>
				<PageTitle pageTitle="搜索"></PageTitle>

				<View className={this.fixed ? 'fixed search-out-box' : 'search-out-box'}>
					<SearchBar onComplate={this.onComplate} value={value}></SearchBar>
				</View>

				{
					latelySearch.length > 0 &&
					<SearchItem title={latelySearchTitle} list={latelySearch} isSearch={true} onRemoveAllSearch={this.onRemoveAllSearch}></SearchItem>
				}
				{
					hotSearch.length > 0 &&
					<SearchItem title={hotSearchTitle} list={hotSearch} ></SearchItem>
				}
			</ScrollView>
		)
	}
}