Почему есть повторяющиеся данные (только 1-й партии) в ответ на выборку в javascript и реагируют на нативную - PullRequest
0 голосов
/ 02 февраля 2020

Я не могу устранить причину повторных данных только первой итерации в моих данных ответа выборки. this.state.productCategories повторяют только начальные идентификаторы в зависимости от значения per_page, которое равно 5 в приведенном ниже примере. Кажется, я применяю правильную логику c, но начальные данные выборки двойные (начальные 5 в приведенном ниже примере). Буду признателен за любую помощь.

Я получаю данные от использования woocommerce список всех категорий продуктов остальные API с per_page=5

Ниже моя реализация

constructor(props) {
        super(props);
        productData = this.props.navigation.getParam('productData');
        base_url = this.props.navigation.getParam('base_url');
        c_key = this.props.navigation.getParam('c_key');
        c_secret = this.props.navigation.getParam('c_secret');
        let selectedProductCategories = []
        productData.categories.forEach(item => {
            selectedProductCategories.push(item.id)
        })
        this.state = {
            loading: false,
            error: null,
            productCategoriesPage: 1,
            hasMoreProductCategoriesToLoad: true,
            productCategories: [],
            selectedProductCategories: selectedProductCategories
        };
    }

   componentDidMount() {
        this.fetchAllProductCategories()
    }

    render() {
        if (this.state.loading) {
            return (
                <View style={{ flex: 1, justifyContent: "center", alignContent: "center", padding: 20 }}>
                    <ActivityIndicator color='#96588a' size='large' />
                </View>
            )
        }

        return (
            <KeyboardAvoidingView style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', }} behavior="padding" enabled>
                <ScrollView>
                    {this.displayProductCategoriesSection()}
                </ScrollView>
                {this.displaySubmitButton()}
            </KeyboardAvoidingView>
        );
    }

    fetchAllProductCategories = () => {
        const url = `${base_url}/wp-json/wc/v3/products/categories?per_page=5&page=${this.state.productCategoriesPage}&consumer_key=${c_key}&consumer_secret=${c_secret}`;
        this.setState({ loading: true });
        fetch(url).then((response) => response.json())
            .then((responseJson) => {
                if (Array.isArray(responseJson) && responseJson.length > 0) {
                    responseJson.forEach((item, index) => {
                        responseJson[index].id = `${item.id}`
                    })
                    responseJson.forEach(item => {
                        console.log(item.name)
                    })
                    this.setState({
                        hasMoreProductCategoriesToLoad: true,
                        productCategoriesPage: this.state.productCategoriesPage + 1,
                        productCategories: this.state.productCategories.concat(responseJson),
                        error: responseJson.code || null,
                        loading: false
                    }, this.fetchAllProductCategories());
                } else {
                    this.setState({
                        hasMoreProductCategoriesToLoad: false
                    })
                }
            }).catch((error) => {
                this.setState({
                    error,
                    loading: false
                })
            });
    }

displayProductCategoriesSection = () => {
        return (
            <View style={styles.section}>
                <Text style={styles.titleText}>Categories</Text>
                <MultiSelect
                    items={this.state.productCategories}
                    uniqueKey="id"
                    displayKey="name"
                    onSelectedItemsChange={selectedItems => this.setState({
                        selectedProductCategories: selectedItems
                    })}
                    hideTags
                    ref={(component) => { this.multiSelect = component }}
                    selectedItems={this.state.selectedProductCategories}
                    selectText="Pick Categories"
                    searchInputPlaceholderText="Search Category..."
                    tagRemoveIconColor="#CCC"
                    tagBorderColor="#CCC"
                    tagTextColor="#CCC"
                    selectedItemTextColor="#CCC"
                    selectedItemIconColor="#CCC"
                    itemTextColor="#000"
                    searchInputStyle={{ color: '#CCC' }}
                    submitButtonColor="#CCC"
                    submitButtonText="Submit"
                />
            </View>
        )
    }


...