gpt4 book ai didi

javascript - 如何使用 redux 为处于某种状态的数组提供唯一 ID

转载 作者:行者123 更新时间:2023-11-28 03:24:04 25 4
gpt4 key购买 nike

所以每次调用我的reduce时,它都应该更新状态。这是有效的,它将新信息推送到新的数组位置。

但现在我想为每个新添加的数组位置添加一个唯一的 ID。问题是它将初始状态从 0 更改为 1,但只更改一次。我希望它增加到 2,3,4,5,....

import {GET_LOCATION} from '../actions/getLocation'
const initialState = {
isLoaded: false,
userLocation: [],
error: null,
time: null,
incident: null,
Id: 0
}
function addNewLocation(state = initialState, action){
switch(action.type){
case GET_LOCATION:
return {
...state,
isLoaded: true,
userLocation:[...state.userLocation, {
latitude: action.payload.position.coords.latitude,
longitude: action.payload.position.coords.longitude,
city: action.payload.area.city,
country: action.payload.area.country,
time: action.payload.time,
incident: action.payload.incident,
story: 'storytime',
userId: state.Id +1
}],
}
default:
return state;
}
}
export default addNewLocation

最佳答案

    import {GET_LOCATION} from '../actions/getLocation'
const initialState = {
isLoaded: false,
userLocation: [],
error: null,
time: null,
incident: null,
Id: 0
}
function addNewLocation(state = initialState, action){
switch(action.type){
const newId = state.Id + 1; // increment ID
case GET_LOCATION:
return {
...state,
Id: newId, // update in state
isLoaded: true,
userLocation:[...state.userLocation, {
latitude: action.payload.position.coords.latitude,
longitude: action.payload.position.coords.longitude,
city: action.payload.area.city,
country: action.payload.area.country,
time: action.payload.time,
incident: action.payload.incident,
story: 'storytime',
userId: newId, // set to the userId
}],
}
default:
return state;
}
}
export default addNewLocation

关于javascript - 如何使用 redux 为处于某种状态的数组提供唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58835678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com