React Native搜索功能无法渲染

时间:2017-10-17 07:26:46

标签: javascript react-native react-native-android react-native-ios

我有两个无法呈现的功能:renderTeachers()renderSubjects()。它们基于状态对象中的教师数组的长度进行渲染。我控制了登录的state.teachers,结果是预期的,数组长度不止一个,但函数仍然没有渲染。我不明白为什么这些功能没有渲染。

class Search extends Component {
  state = {
    teachers: [],
    subjects: [],
    rating: 3.5,
  };

  requestData = (queryObj) => {
    console.log(queryObj);
    const client = algoliasearch('__ID__', '__KEY__');
    const queries = [{
      indexName: 'teachers',
      query: queryObj,
      filters: 'Rating >= 3.5',
    }, {
      indexName: 'subjects',
      query: queryObj,
    }];
    if (queryObj === '') {
      this.setState({ showSearchVal: false });
    } else {
      client.search(queries, this.searchCallback.bind(this));
    }
  }

  searchCallback = (err, content) => {
    if (err) {
      console.error(err);
      return;
    }
    this.setState({ teachers: content.results[0].hits, subjects: content.results[1].hits });
  }

  renderSubjects = () => {
    if (this.state.subjects.length >= 1) {
      return this.state.subjects.map(subject => <SubjectDetail key={subject.objectID} subject={subject} />);
    }
    return null;
  }

  renderTeachers = () => {
    console.log('in');
    if (this.state.teachers.length >= 1) {
      return this.state.teachers.map(teacher => <SearchDetail key={teacher.UID} person={teacher} />);
    }
    return null;
  }

  render() {
    return (
      <View>
        <Header search onPress={() => this.searchBar.show()} />
        <SearchBar
          backgroundColor='#02254e'
          iconColor='#4f5d6d'
          placeholderTextColor='#4f5d6d'
          backButton={<Icon name='keyboard-backspace' size={24} color='#4f5d6d' style={{ alignSelf: 'center' }} />}
          textColor='white'
          animate={false}
          handleChangeText={this.requestData}
          selectionColor='#01152d'
          fontFamily='avenir_heavy'
          backCloseSize={24}
          ref={(ref) => { this.searchBar = ref; }}
        />
        <View style={{ width, height, alignItems: 'center', flex: 1 }}>
          <ScrollView style={{ flex: 1 }}>
            <Text style={styles.topResultTextStyle}>
              {this.state.subjects.length >= 1 ? 'Subjects' : ''}
            </Text>
            {this.renderSubjects()}
            <Text style={styles.topResultTextStyle}>
              {this.state.teachers.length >= 1 ? 'Teachers' : ''}
            </Text>
            {this.renderTeachers()}
          </ScrollView>
        </View>
      </View>
    );
  }
}

export { Search };

1 个答案:

答案 0 :(得分:0)

从您发布的代码中,我无法看到教师/主题无法呈现的原因。我的问题是,你如何设置教师/科目数组?在不改变状态/道具的情况下,反应组件不应该渲染。你能分享一下阵列集代码吗?