【问题标题】:scrollToIndex out of range: request index1 but maximum is -1 .. React NativescrollToIndex 超出范围:请求 index1 但最大值为 -1 .. React Native
【发布时间】:2021-06-16 04:23:50
【问题描述】:

当我运行我的应用程序时,如果我创建一个数组并将其放入 FlatList 中的数据中,就像这个数组一样

const photos = [
  { id: 1, title: "Photo 1" },
  { id: 2, title: "Photo 2" },
  { id: 3, title: "Photo 3" },
  { id: 4, title: "Photo 4" },
  { id: 5, title: "Photo 5" },
  { id: 6, title: "Photo 6" },
];

但是当我用 API 替换照片数组时,应用程序无法运行。我尝试的不仅仅是 API,我认为错误出在我的代码中,而不是在 API 中, 这个错误在我看来“scrollToIndex out of range: request index1 but maximum is -1” 我的代码有什么问题?

import React, { useState, useRef, useEffect } from "react";
import {
  StyleSheet,
  View,
  FlatList,
  Dimensions,
  Text,
  TouchableOpacity,
} from "react-native";
import { AntDesign } from "@expo/vector-icons";

import axios from "axios";


const phoneWidth = Dimensions.get("screen").width;
const phoneHeight = Dimensions.get("screen").height;

function ScrollScreen() {
  const [index, setIndex] = useState(0);
  const [border, setBorder] = useState(0);
  const refContainer = useRef();
  const refBox = useRef();

  const [data, setData] = useState([]);
  useEffect(() => {
    photos();
  }, []);

  function photos() {
    axios
      .get("https://jsonplaceholder.typicode.com/photos")
      .then(async function (response) {
        setData(response.data);
      })
      .catch((err) => console.error(err));
  }

  useEffect(() => {
    refContainer.current.scrollToIndex({ animated: true, index }); 
  }, [index]);

  useEffect(() => {
    refBox.current.scrollToIndex({ animated: true, index }); 
  }, [index]);

  const theNext = () => {
    if (index < photos.length - 1) {
      setIndex(index + 1);
      setBorder(index + 1);
    }
  };
  const thePrevious = () => {
    if (index > 0) {
      setIndex(index - 1);
      setBorder(index - 1);
    }
  };

  return (
    <View style={styles.con}>
      <AntDesign
        style={[styles.iconConPosition, { left: phoneWidth * 0.05 }]}
        onPress={thePrevious}
        size={55}
        color="#0dddcb"
        name="caretleft"
      />

      <AntDesign
        style={[styles.iconConPosition, { right: phoneWidth * 0.05 }]}
        onPress={theNext}
        size={55}
        color="#0dddcb"
        name="caretright"
      />

      <FlatList
        scrollEnabled={false}
        ref={refContainer}
        data={data}
        // data={photos}
        keyExtractor={(item, index) => item.id.toString()}
        style={styles.flatList}
        renderItem={({ item, index }) => (
          <View
            style={{
              height: 150,
              width: phoneWidth * 0.7,
              margin: 50,
              backgroundColor: "red",
              alignSelf: "center",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Text>{item.id}</Text>
            <Text>{item.title}</Text>
          </View>
        )}
        horizontal
        pagingEnabled //تفعيل خاصية التمرير
        showsHorizontalScrollIndicator={false} 
      />

      <FlatList
        ref={refBox}
        data={data}
        // data={photos}
        keyExtractor={(item, index) => item.id.toString()}
        style={styles.flatList}
        renderItem={({ item, index }) => (
          <TouchableOpacity
            onPress={() => {
              setIndex(index);
              setBorder(index);
            }}
            style={
              border === index
                ? {
                    height: 100,
                    width: phoneWidth * 0.4,
                    margin: 7,
                    backgroundColor: "gray",
                    alignSelf: "center",
                    justifyContent: "center",
                    alignItems: "center",
                    borderWidth: 2,
                    borderColor: "blue",
                  }
                : {
                    height: 100,
                    width: phoneWidth * 0.4,
                    margin: 7,
                    backgroundColor: "gray",
                    alignSelf: "center",
                    justifyContent: "center",
                    alignItems: "center",
                  }
            }
          >
            <Text>{item.id}</Text>
            <Text>{item.title}</Text>
          </TouchableOpacity>
        )}
        horizontal
      />
      <Text>{index}</Text>
    </View>
  );
}
export default ScrollScreen;

【问题讨论】:

  • 表示在scrollToIndex方法中'index'为1,但不能高于-1。此错误似乎与您提到的数组无关。

标签: javascript arrays reactjs react-native indexing


【解决方案1】:

最初data 是一个空数组,但index 设置为0。在第一次调用尝试滚动的useEffect 时,出现错误,因为scrollToIndex(0)data 为空时出错,因为没有索引0 的项目。

尝试将borderindex 状态初始化为-1 而不是0,例如:

  const [index, setIndex] = useState(-1);
  const [border, setBorder] = useState(-1);

在单独但相关的注释中,theNext 函数有一个错误,它应该检查 data.length 而不是 photos.length

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 2021-04-29
    • 2015-08-06
    • 2013-12-14
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 2021-05-16
    相关资源
    最近更新 更多