我有一个简单的组件,其中包含一个动物名称数组(牛、马、鸡)和一个按钮,当单击该按钮时,该数组的索引将增加以显示下一个动物的名称。我想知道一旦到达数组的末尾,我就可以重定向用户。我怎样才能做到这一点呢?
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!")
}
}
任何帮助都将非常感激!
你差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>
当您点击handleClick
功能时,index
状态将被更新1。根据handleClick
函数内部应用的条件,每当index
状态数达到等于或超过数组中存在的元素数时,它将显示一个警报。
const handleClick = () => {
setindex(index + 1)
if (index >= array.length - 1 ) {
alert("We've reached the end of the array, redirect user!")
}
}