你好,我需要一些关于 react-redux 的帮助,因为我还在学习,假设我正在尝试进行简单的队列管理,并且我有这个 reducer :
const initialState = {
currentQueue = {},
queues=[],
loading: false
}
数据会是这样的:
currentQueue:
{{'id_queue': '1', 'queue_no': 'A001', 'status': 0}}
queues:
[0:{'id_queue': 1, 'queue_no': 'A001', 'status': 0 },
1:{'id_queue': 2, 'queue_no': 'A002', 'status': 0 }]
如何从 queues 数组中获取单个对象到 currentQueue ?就像下一个队列一样,我只知道通过 id 获取对象(比如人物资料)。所以我需要一个一个地呈现队列数组列表以显示当前队列号,或者我应该只将 mysql 查询限制操作 1?。
请赐教如何在react-redux中用mysql实现正确的队列,如果有更好的方法,谢谢。因为我已经尝试使用 react-redux 搜索一些队列实现,但没有成功。
最佳答案
javascript 数组可以像 fifo queue 一样工作.
const fifo = [];
fifo.push(1)
fifo.push(2)
console.log(fifo.push(3)) // undefined
console.log(fifo) // [1, 2, 3]
const val = fifo.shift()
console.log(val, fifo) // 1, [2, 3]
但是 push、pop、unshift 和shift 都会改变数组。这是一个 immutable way .
function immutablePush(arr, newEntry){
return [ ...arr, newEntry ]
}
function immutableShift(arr){
return arr.slice(1)
}
const fifo = [];
immutablePush(fifo, 1) // returns [1]
immutablePush(fifo, 2) // [1, 2]
immutablePush(fifo, 3) // [1, 2, 3]
const val = fifo[0] // 1
immutalbeShift(fifo) // returns [2, 3]
如果你想像在对象中那样查找数据,你需要 normalize data .
在大多数情况下,您可以简单地使用 findIndex
const findByIdQueue(array, id) => {
const i = array.findIndex(item => item.id_queue === id);
// if i = -1 (not found) return undefined else return found item
return ~i ? undefined : array[i];
}
在 React redux 中,我们希望将访问和更新代码分开。我们使用选择器访问:
const selectFirstItem = state => {
// access state.fifo but set fifo to [] if state or state.fifo are undefined
const { fifo = [] } = state || {};
// return first array item or undefined if there is an empty list
return fifo[0];
}
const selectItemById = (state, ownProp) => {
const { fifo = [] } = state || {};
const { id } = ownProp || {};
return findByIdQueue(fifo, id);
}
const mapStateToProps = (state, ownProp) => ({
firstItem = selectFirstItem(state);
itemById = select(state, ownProp) // expect parent of MyCoolControl to pass in prop id
// <MyCoolControl id={24} />
})
export default connect(mapStateToProps)(MyCoolControl)
我们更新 Action :
const addItem = item => ({type: 'ADD_ITEM', item})
const removeFirstItem = () => ({type: 'REMOVE_FIRST_ITEM'})
const fifoReducer = (prev = defaultValue, action = {}) => {
const { type, item} = action;
switch (type) {
case "ADD_ITEM":
return [...prev, item];
case "REMOVE_FIRST_ITEM":
return prev.slice(1);
default: {
return prev;
}
}
};
关于javascript - 如何用Reactjs&Redux实现fifo队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58844583/