代码之家  ›  专栏  ›  技术社区  ›  Ollie Lynas

循环浏览列表中的选项时,仅显示最后一个选项(显示两次)和倒数第二个选项(react native JS)

  •  0
  • Ollie Lynas  · 技术社区  · 3 年前

    cycleLeft() cycleRight() ,但我得到的是第二个倒数第二个选项,它在一行中显示两次,然后最后一个选项显示一次。 这适用于主应用程序功能中的react本机应用程序。感谢您的帮助。

    var gamesList = ["Quadratic", "Magic Square", "Settings", "Option 3"];
    var index = 0;
    var game = gamesList[index];
    
    const [gameText, setGameText] = useState(gamesList[index]);
    const [gameGame, setGameGame] = useState(gamesList[index]);
    const zAnim = useRef(new Animated.ValueXY({ x: 0, y: 1000 })).current;
    
    const cycleLeft  = () =>  {
      index = index - 1;
      if (index < 0) { index = gamesList.length - 1; };
      game = gamesList[index];
      setGameText(gamesList[index]);
      console.log(game + " " + index);
    }
    
    const cycleRight = () => {
      index = index + 1;
      if (index > gamesList.length - 1) { index = 0; };
      game = gamesList[index];
      setGameText(gamesList[index]);
      console.log(game + " " + index);
    }
    

    Console Log

    1 回复  |  直到 3 年前
        1
  •  1
  •   wxker    3 年前

    index 应该是有状态的,而不是 gameText

    var gamesList = ["Quadratic", "Magic Square", "Settings", "Option 3"];
    const [index, setIndex] = useState(0);
    
    const cycleLeft  = () =>  {
      setIndex(prevIndex => prevIndex - 1 < 0 ? gamesList.length - 1 : prevIndex - 1);
    }
    
    const cycleRight = () => {
      setIndex(prevIndex => prevIndex + 1 > gamesList.length - 1 ? 0 : prevIndex + 1);
    }
    
    //just for logging
    useEffect(() => {
      console.log(gamesList[index]+ " " + index);
    }, [index]);
    

    无论你在哪里使用 游戏文本 ,你可以用 gamesList[index] 相反