我试图通过使用object.assign向每个运动对象添加一个标识符键,但是,如果我添加同一对象的多个倍数。
新的object.assign会覆盖所有具有相同名称的键(directId)。我尝试过使用循环,映射,将时间戳记添加到键中,以查看如果对象完全相同,则uuidv1是否给出相同的keyid,但我不相信这是正确的。
似乎与object.assign有关。
该函数在每次按下新对象时运行,而uuidv1()是唯一的密钥生成器。
不确定接下来要尝试什么。
saveDataToWorkout = obj => {
const objWithId = Object.assign(obj, { directId: uuidv1() });
this.setState({
pendingSavedArr: [...this.state.pendingSavedArr, objWithId]
});
};
04:16:45: Array [
04:16:45: Object {
04:16:45: "avatarURL": 16,
04:16:45: "difficulty": "Easy",
04:16:45: "directId": "d50d5310-c7ad-11e8-a726-e942788f9851",
04:16:45: "equipment": "Machine",
04:16:45: "estimatedTime": 5,
04:16:45: "muscleGroup": "Shoulders and Traps",
04:16:45: "title": "Leverage Shrug",
04:16:45: },
04:16:45: Object {
04:16:45: "avatarURL": 16,
04:16:45: "difficulty": "Easy",
04:16:45: "directId": "d61e4de0-c7ad-11e8-a726-e942788f9851",
04:16:45: "equipment": "Machine",
04:16:45: "estimatedTime": 5,
04:16:45: "muscleGroup": "Shoulders and Traps",
04:16:45: "title": "Smith Machine Shrug",
04:16:45: },
04:16:45: ]
在传递到反应状态之前,应通过对象分配添加唯一键。
04:16:46: Array [
04:16:46: Object {
04:16:46: "avatarURL": 16,
04:16:46: "difficulty": "Easy",
04:16:46: "directId": "d50d5310-c7ad-11e8-a726-e942788f9851",
04:16:46: "equipment": "Machine",
04:16:46: "estimatedTime": 5,
04:16:46: "muscleGroup": "Shoulders and Traps",
04:16:46: "title": "Leverage Shrug",
04:16:46: },
04:16:46: Object {
04:16:46: "avatarURL": 16,
04:16:46: "difficulty": "Easy",
04:16:46: "directId": "d61e4de0-c7ad-11e8-a726-e942788f9851",
04:16:46: "equipment": "Machine",
04:16:46: "estimatedTime": 5,
04:16:46: "muscleGroup": "Shoulders and Traps",
04:16:46: "title": "Smith Machine Shrug",
04:16:46: },
04:16:46: Object {
04:16:46: "avatarURL": 16,
04:16:46: "difficulty": "Easy",
04:16:46: "directId": "d6924560-c7ad-11e8-a726-e942788f9851",
04:16:46: "equipment": "Dumbbell",
04:16:46: "estimatedTime": 5,
04:16:46: "muscleGroup": "Shoulders and Traps",
04:16:46: "title": "Smith Machine Behind the Back Shrug",
04:16:46: },
04:16:46: ]
答案 0 :(得分:1)
您可以将值分配给一个空对象,以防止对结果数组的相同引用。
const objWithId = Object.assign({}, obj, { directId: uuidv1() });