repeat-step算法反应javascript



我想制作一个类似的重复数组

1->2->3->1->2->3.....
const [current,setCurrent] = useState(0);
const [direction,setDirection] = useState()
const prevCurrent = usePrevious(current)
const maxData = 3;
function handler(val){
if(val==='plus'){
current !== maxData ? setCurrent(prev=>prev+1):setCurrent(0)
}else{
current !== 0 ? setCurrent(prev=>prev-1):setCurrent(maxData)
}
}
useEffect(()=>{
if(current>prev){
setDirection('next')
} else{
setDirection('prev')
}
},[current])

return <div>
<button onClick={()=>handler('plus')}>+</button>
<button onClick={()=>handler('min')}>-</button>
<span>{direction}</span>
</div>

在这种情况下,我总是想重复我的电流,例如,如果新电流是2,prev电流是1,那么方向将是下一个,但当电流是最后一步,并且电流将设置为0时,但方向将设置为"prev",因为current<上一个,但我希望我的方向仍然设置为下一个。

有什么算法可以解决这个问题吗?

认为我理解你在寻找什么。如果是这样,那么您应该能够简单地从处理程序中调用setDirection,类似于以下内容:

const {useState, useEffect} = React;
const MyComponent = () => {
const [current, setCurrent] = useState (0)
const [direction, setDirection] = useState ('?')
const maxData = 3
function handler (val){
if (val === 'plus'){
setDirection ('next')
current !== maxData ? setCurrent (prev => prev + 1) : setCurrent (0)
} else {
setDirection ('prev')
current !== 0 ? setCurrent (prev => prev - 1): setCurrent (maxData)
}
}
return <div>
<button onClick={() => handler ('plus')}>+</button>
<button onClick={() => handler ('min')}>-</button>
<p>{current} ({direction})</p>
</div>
}
ReactDOM.render(
<MyComponent />,
document.getElementById("react")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

但我认为你也可以通过做两件事来清理这件事。首先,跳过"plus""min"字符串,改为使用+1-1。其次,保留一个要循环的值数组,并使current索引跟踪到该数组中,使用真模函数将其环绕到数组的开始/结束。。请注意,余数运算符-%不是真模,因为它不能正确处理负操作数。

const {useState, useEffect} = React;
const mod = (n, m) => ((n % m) + m) % m
const MyComponent = () => {
const [current, setCurrent] = useState (0)
const [direction, setDirection] = useState ('?')

const options = [1, 2, 3]

const handler = (delta) => {
setCurrent ((prev) => mod (prev + delta,  options .length))
setDirection (() => delta > 0 ? 'next' : 'prev') 
console .log ({delta, current, option: options[current]})
}
return <div>
<button onClick = {() => handler (+1)}>+</button>
<button onClick = {() => handler (-1)}>-</button>
<p>{options [current]} ({direction})</p>
</div>
}
ReactDOM.render(
<MyComponent />,
document.getElementById("react")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

最新更新