Hil*_*ano 4 javascript reactjs redux
你好,我需要一些关于 react-redux 的帮助,因为我还在学习,假设我正在尝试制作简单的队列管理,我有这个减速器:
const initialState = {
currentQueue = {},
queues=[],
loading: false
}
Run Code Online (Sandbox Code Playgroud)
数据如下:
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 }]
Run Code Online (Sandbox Code Playgroud)
如何从队列数组中获取单个对象到currentQueue?就像下一个队列一样,我只知道通过 id 获取对象(比如人的个人资料)。所以我需要一一呈现队列数组列表以显示当前队列号,或者我应该将 mysql 查询限制操作 1 吗?
如果有更好的方法,请赐教我在react-redux中使用mysql实现正确的队列,谢谢。因为我已经尝试使用 react-redux 搜索一些队列实现但没有运气。
javascript 数组可以像一个先进先出队列。
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]
Run Code Online (Sandbox Code Playgroud)
然而, push、pop、unshift 和 shift 都会改变数组。这是一个不变的方式。
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]
Run Code Online (Sandbox Code Playgroud)
如果要像在对象中一样查找数据,则需要规范化 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];
}
Run Code Online (Sandbox Code Playgroud)
在 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)
Run Code Online (Sandbox Code Playgroud)
我们用行动更新:
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;
}
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1392 次 |
最近记录: |