我正在尝试显示时间列表(例如 07:00、07:30),但是当出现重复时间时,显示其旁边的重复次数(例如 07:30、08:00³)
当我遍历一个列表时,每个项目都需要自己的状态,以便可以在每个时间旁边设置和显示计数器
目前,我遇到了太多重新渲染的问题,但我也不确定我的减速器是否正确
没有任何注释的代码可以在这个 repo 中看到:https ://github.com/charles7771/decrease-number-wont-work/blob/master/index.js
const TimeGrid = () => {
const reducer = (state, action) => {
switch(action.type) {
case 'SET_COUNTER':
return {
...state,
[`counter${action.id}`]: action.payload
}
default:
return state
}
}
//not sure if this bit is correct
let [{ counter }, dispatchReducer] = useReducer(reducer, {
counter: '',
})
我的上下文导入和 allBookedTimes
const { theme, timesUnavailable,
removeFromTimesUnavailable,
addToTimesUnavailable } = useContext(Context)
const allBookedTimes = allBookings.map(element => element.time)
//below, both have been mapped out of a JSON file
const extractedTimesOnly = availableTimesJSON.map(item => item.time)
const availableTimes = availableTimesJSON.map(item => item)
我有有用的功能来计算时间重复的次数
//used to count instances. (e.g. 22:30: 3, 23:00: 1)
const counts = {}
extractedTimesOnly.forEach(x => {
counts[x] = (counts[x] || 0) + 1
})
//used to not repeat a Time
const timeAlreadyDisplayed = []
这就是我用来循环遍历 Time 列表并显示每个 Time 及其旁边的计数器的逻辑,以及尝试通过单击来减少计数器。
const displayAvailableTimes = availableTimes.map((item, index) => {
//tries to set the value of counter0 (or counter1, ... counterN)
//to the number of instances it appears,
//too many rerenders occurs...
dispatchReducer({
type: 'SET_COUNTER',
id: item.id,
payload: counts[`${item.time}`] //doesn't seem to be working. tried logging it and it shows nothing
})
//counter = counts[`${item.time}`] -----> works, but then I am not doing this through the dispatcher
//maybe this logic could be flawed too?
if (index > 0 &&
item.time === availableTimes[index - 1].time &&
item.time !== availableTimes[index - 2].time) {
return (
//tries to show the counter below
<span> {counter} </span>
)
}
else if (item.time > currentTime - 10 && !timeAlreadyDisplayed[item.time]) {
timeAlreadyDisplayed[item.time] = true
return (
<li
key={item.id}
id={item.id}
onClick={() => {
//tries to decrease the counter, I don't think it works
counter > 1 ? dispatchReducer({
type: 'SET_COUNTER',
id: item.id,
payload: counter - 1
}) :
allBookedTimes.includes(item.time) && item.day === 'today'
? void 0
timesUnavailable.includes(item)
? removeFromTimesUnavailable(item)
: addToTimesUnavailable(item)
}}>
{item.time}
</li>
)
}
return null
})
return (
<>
<ul>{displayAvailableTimes}</ul>
</>
)
}