【问题标题】:How do I detect when I've reached the end of an array in a react functional component?如何检测何时到达反应功能组件中的数组末尾?
【发布时间】:2021-04-19 05:03:38
【问题描述】:

我有一个简单的组件,其中包含一组动物名称(牛、马、鸡)和一个按钮,当单击该按钮时,会增加数组的索引以显示下一个动物的名称。我想知道一旦我到达数组的末尾,以便我可以重定向用户。我怎样才能做到这一点?

import React, { useState } from 'react'

export default function Test() {

    const [array, setArray] = useState(['cow', 'horse', 'chicken'])
    const [index, setIndex] = useState(0)

    const handleClick = () => {
        setIndex(prevIndex => prevIndex + 1)
    }

    return (
        <div>
            <button onClick={handleClick}>Next animal</button>
            <h2>{array[index]}</h2>
        </div>
    )
}

我曾尝试按照以下几行向回调函数添加条件语句,但它不起作用:

const handleClick = () => {
    if(index < array.length){
        setIndex(prevIndex => prevIndex + 1)
    } else {
        alert("We've reached the end of the array, redirect user!")
    }
}

任何帮助将不胜感激!

【问题讨论】:

  • 您是否希望在下一次单击将索引出数组时导航用户?或者当他们到达最后一个元素时?
  • 是的,我想在下一次点击索引出数组时导航用户。

标签: arrays reactjs indexing use-state react-functional-component


【解决方案1】:

你差了 1 个。最后一个索引是 array.length - 1,所以比较一下:

const App = () => {
    const [array, setArray] = React.useState(['cow', 'horse', 'chicken'])
    const [index, setIndex] = React.useState(0)

    const handleClick = () => {
        if(index === array.length - 1){
            alert("We've reached the end of the array, redirect user!")
        } else {
            setIndex(index + 1);
        }
    }

    return (
        <div>
            <button onClick={handleClick}>Next animal</button>
            <h2>{array[index]}</h2>
        </div>
    )
};

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

【讨论】:

  • 查看实时 sn-p,它看起来可以正常工作?
  • "在回调中调用时的索引值始终是最初设置的值" 为什么会这样?此行为仅在您使用 useCallback 时存在,但即使您需要在依赖项数组中包含 index,它也会按预期工作
【解决方案2】:

每当您点击handleClick 函数时,index 状态将更新一。根据handleClick 函数内部应用的条件,每当index 状态数达到等于数组中存在的元素数时,它将显示警报。

const handleClick = () => {
    setindex(index + 1)
    if (index >= array.length - 1 ) {
        alert("We've reached the end of the array, redirect user!")
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2018-08-24
    相关资源
    最近更新 更多