Как развернуть и свернуть указанный раздел с помощью SecionList? - PullRequest
0 голосов
/ 30 мая 2018

Я вызываю API https://obscure -reaches-65656.herokuapp.com / api / getCloseTime? City = Miaoli & sTime = 21 & eTime = 24 для моего действия react-redux и использую SectionList, чтобы показатьdata.

В официальном уроке я использую SectionList, он просто покажет весь раздел, я пытаюсь найти способ щелкнуть заголовок, который может развернуть или свернуть раздел.

Iнайдите, что мои sectionComp и renderSectionItem используют один и тот же заголовок, поэтому я пытаюсь использовать this.state{ title: '', expand: false }

Когда я нажимаю 國興戲院, используйте this.setState({ title: '國興戲院', expand: true }) и используйте как if(this.state.expand) {} в renderSectionItem

Очевидно, что это не работает, потому что у меня может быть много разделов.

Я понятия не имею, какой следующий шаг я должен попробовать.

Любая помощь будет оценена.Заранее спасибо.

Вот мои данные SectionList: enter image description here

Вот мой компонент класса:

import React, { Component } from 'react';
import { Text, SectionList, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import { View } from 'react-native-animatable';
import { fetchSearchTime } from '../actions';
import { Spinner } from './common';
import GetUserTime from '../function/common/GetUserTime';

class MovieCloseTime extends Component {
  constructor(props) {
    super(props);
    const { selectedCity, firstSliderValue, secondSliderValue } 
    = this.props.navigation.state.params;
    this.state = { 
      selectedCity, 
      firstSliderValue, 
      secondSliderValue,
    };
  }

  componentDidMount() {
    const { selectedCity, firstSliderValue, secondSliderValue } = this.state;

    this.props.fetchSearchTime({ 
        selectedCity, firstSliderValue, secondSliderValue
    });
  }

  sectionComp = (info) => {
    const theaterCn = info.section.title;
    console.log('Title info is =>');
    console.log(info);
    return (
      <TouchableOpacity 
        onPress={() => console.log('Hot to expand and collapse specify section when click here?')}
      >
        <View style={{ flex: 1, backgroundColor: '#DCDCDC' }}>
          <Text style={styles.sectionTitle}>{theaterCn}</Text>
        </View>
      </TouchableOpacity>
    );
  }

  renderSectionItem = (info) => {
    const cnName = info.item.cnName;
    console.log('Section info is =>');
    console.log(info);

    return (
      <TouchableOpacity 
        onPress={() => {
        this.props.navigation.navigate('MovieDetail', {
          enCity: this.state.selectedCity,
          cnName
          });
        }
        }
      >
      <View style={{ flex: 1, flexDirection: 'column' }}>

        <Text style={styles.sectionSubTitle}>{cnName}</Text>

        <View style={{ flexDirection: 'row', flexWrap: 'wrap', backgroundColor: '#F8F8FF' }}>
        {info.item.releasedTime.map((value, index) => {
          const theTime = GetUserTime.getAsiaTime(value, 'YYYY/MM/DD HH:mm:ss');
          const hour = theTime.getHours();            
          const minute = (theTime.getMinutes() < 10 ? '0' : '') + theTime.getMinutes();
          return (
            <Text style={styles.sectionTimeTitle} key={index}>{`${hour}:${minute}`}</Text>
          );
        })
        }
        </View>
      </View>
      </TouchableOpacity>
    );
  }

  render() {
    const movieData = this.props.searchTime;
    if (this.props.loading) {
      return <Spinner text='Loading...' />;
    }
    console.log('movieData is =>');
    console.log(movieData);

    return (
      <View style={{ flex: 1 }}>
        <SectionList
          renderSectionHeader={this.sectionComp}
          renderItem={this.renderSectionItem}
          sections={movieData}
          keyExtractor={(item, index) => index}
          ItemSeparatorComponent={() => <View style={styles.separator} />}
        />
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  const searchTime = state.searchTime.searchList;
  const loading = state.searchTime.loading;

  return { searchTime, loading };
};

const styles = {
  // some styles
};


export default connect(mapStateToProps, { fetchSearchTime })(MovieCloseTime);

Вот мое действиеfetchSearchTime:

export const fetchSearchTime = ({ selectedCity, firstSliderValue, secondSliderValue }) => {
  return (dispatch) => {
    dispatch({ type: SEARCH_TIME_REQUEST });
    console.log(`https://obscure-reaches-65656.herokuapp.com/api/getCloseTime?city=${selectedCity}&sTime=${firstSliderValue}&eTime=${secondSliderValue}`);
    fetch(`https://obscure-reaches-65656.herokuapp.com/api/getCloseTime?city=${selectedCity}&sTime=${firstSliderValue}&eTime=${secondSliderValue}`)
      .then(response => response.json())
      .then(responseData => {
        const movieData = responseData.reduce((r, s) => {
          r.push({ title: s.theaterCn, id: s._id, expand: true, data: s.movie });
          return r;
        }, []);
        //dispatch({ type: SEARCH_TIME, payload: responseData });
        dispatch({ type: SEARCH_TIME, payload: movieData });
      })
      .catch((error) => console.log(error));    
    };  
};

о типе SEARCH_TIME редуктор:

// with others type
import { 
  SEARCH_TIME_REQUEST,
  SEARCH_TIME
} from '../actions/types';

const INITIAL_STATE = {
  searchList: [],
  loading: true,
  selectedCity: '',
  firstSliderValue: '',
  secondSliderValue: ''
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case SEARCH_TIME_REQUEST:
      return {
        searchList: [],
        loading: true,
      };
    case SEARCH_TIME:
      return {
        searchList: action.payload,
        loading: false
      };
    default:
      return state;
  }
};
...