每次都调用dataSuccess函数

时间:2019-03-22 13:20:03

标签: javascript reactjs react-native react-native-elements

我正在使用React Native Elements搜索栏。每次我呼叫他时,都会调用dataSuccess函数。搜索时,只有searchLead功能需要工作。

我已经阅读了React本机元素搜索栏文档。仍然没有用。我认为我的算法有问题。我希望我能告诉。有没有使用搜索栏的更好示例?

我与您共享所有代码。

预先感谢您的帮助。

export default class Lead extends Component {
  constructor (props) {
    super(props);

    this.state = {
      isLoading: true,
      isRefreshing: false,
      searchText: '',
      isSearch: false,
      offset: 0,
      maxSize: 10,
      leadList: [],
      searchData: []
    };
  }

  componentWillMount () {
    this.setState({ isLoading: true });
  }

  componentDidMount () {
    this.loadData();
  }

  handleRefresh = () => {
    this.setState({
      offset: 0,
      maxSize: 10,
      isSearch: false,
      isRefreshing: true
    }, () => {
      this.loadData();
    });
  };

  handleLoadMore = () => {
    this.setState({
      maxSize: this.state.maxSize + 5
    }, () => {
      this.loadData();
    });
  };

  keyExtractor = (item, index) => index.toString();

  loadData = async () => {
    try {
      const { offset, maxSize } = this.state;

      const username = await AsyncStorage.getItem('username');
      const token = await AsyncStorage.getItem('token');

      var credentials = Base64.btoa(username + ':' + token);
      var URL = `http://demo.espocrm.com/advanced/api/v1/Lead?sortBy=createdAt&asc&offset=${offset}&maxSize=${maxSize}`;

      axios.get(URL, { headers: { 'Espo-Authorization': credentials } })
        .then(this.dataSuccess.bind(this))
        .catch(this.dataFail.bind(this));
    } catch (error) {
      Alert.alert(
        'Hata',
        'Bir hata meydana geldi. Lütfen yöneticiye başvurunuz.',
        [
          { text: 'Tamam', onPress: () => null }
        ]
      );
    }
  };

  searchLead = async (text) => {
    try {
      if (text) {
        this.setState({ searchText: text, isSearch: true, isLoading: true });

        const { searchText, maxSize } = this.state;
        const username = await AsyncStorage.getItem('username');
        const token = await AsyncStorage.getItem('token');

        var credentials = Base64.btoa(username + ':' + token);
        var URL = `http://demo.espocrm.com/advanced/api/v1/Lead?select=name&orderBy=createdAt&order=desc&where[0][type]=textFilter&where[0][value]=${searchText}&maxSize=${maxSize}`;

        axios.get(URL, { headers: { 'Espo-Authorization': credentials } })
          .then(this.dataSearch.bind(this))
          .catch(this.dataFail.bind(this));
      }
    } catch (error) {
      Alert.alert(
        'Hata',
        'Arama başarısız oldu. Lütfen yöneticiniz ile görüşün.',
        [
          { text: 'Tamam', onPress: () => null }
        ]
      );
    }
  }

  dataSuccess (response) {
    console.log('test');
    this.setState({ isRefreshing: false, isLoading: false, leadList: response.data.list });
  }

  dataSearch (response) {
    this.setState({ isRefreshing: false, isLoading: false, isSearch: true, searchData: response.data.list });
  }

  dataFail (error) {
    this.setState({ isLoading: false });

    Alert.alert(
      'Hata',
      'Beklenmedik bir hata oluştu',
      [
        { text: 'Tamam', onPress: () => null }
      ]
    );
  }

  render () {
    const { isLoading, isRefreshing, searchText, isSearch, leadList, searchData } = this.state;
    return (
      <View style={styles.container}>
        <SearchBar
          placeholder="Bir lead arayın..."
          onChangeText={this.searchLead.bind(this)}
          value={searchText}
        />
        {
          isLoading ? <ActivityIndicator style={styles.loading} size="large" color="orange" />
            : isSearch
              ? <FlatList
                data={searchData}
                renderItem={({ item }) =>
                  <ListItem
                    leftAvatar={{ source: { uri: 'https://pbs.twimg.com/profile_images/567081964402790401/p7WTZ0Ef_400x400.png' } }}
                    title={item.name}
                    subtitle={item.status}
                    bottomDivider={true}
                  />
                }
                keyExtractor={this.keyExtractor}
                refreshing={isRefreshing}
                onRefresh={this.handleRefresh}
                onEndReached={this.handleLoadMore}
                onEndReachedThreshold={0.5}
              />
              : <FlatList
                data={leadList}
                renderItem={({ item }) =>
                  <ListItem
                    leftAvatar={{ source: { uri: 'https://pbs.twimg.com/profile_images/567081964402790401/p7WTZ0Ef_400x400.png' } }}
                    title={item.name}
                    subtitle={item.status}
                    bottomDivider={true}
                  />
                }
                keyExtractor={this.keyExtractor}
                refreshing={isRefreshing}
                onRefresh={this.handleRefresh}
                onEndReached={this.handleLoadMore}
                onEndReachedThreshold={0.5}
              />
        }
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

setState是一个异步函数,如果要在设置状态变量后立即使用它。

您应该使用setState回调参数函数,该函数将在状态更新后触发。 this.setState({ foo: 'bar' }, () => console.log(this.state.foo))

看看下面的代码

this.setState({ searchText: text, isSearch: true, isLoading: true }, async () => {
  const { searchText, maxSize } = this.state;
  const username = await AsyncStorage.getItem('username');
  const token = await AsyncStorage.getItem('token');
  // ...
});