我正在通过react-redux调用对象数组,并将它们设置为与programList相等,在更高级别的组件上,然后将其传递到这里,我通过find()将找到的对象ID设置为变量,而我正在尝试来记录信息。
当我调用programList时,这很好,有时当我调用selectedProgram时,它将显示为未定义的,已经很奇怪了,因为我上周从未发生过这种情况。
最重要的是,当我只想测试是否可以使用selectedProgram.title从单个返回的对象(selectedProgram)中获取标题时,我会得到未定义,而当我执行Object.keys(会得到未定义)时。
我尝试将其放入新的Promise中,并且可以使用,但是我也收到未解决的Promise警告。但是我不知所措,因为我没有更改此特定代码,但无法正常工作。
20:23:32: Incoming Program Id: 5e8860c0-cbe7-11e8-bca0-b7f8a21d1c09
20:23:32: 5e8860c0-cbe7-11e8-bca0-b7f8a21d1c09 5e8860c0-cbe7-11e8-bca0-b7f8a21d1c09
const Workout = ({ programList, programId }) => {
// find the correct programlist with same id as navId for mapping
const selectedProgram = programList.find(index => {
if (index.id === programId) {
console.log(programId, index.id);
return index;
}
});
// const workoutListArr = selectedProgram;
console.log("this is the original list", programList);
console.log("this is object: ", selectedProgram);
console.log("this is here: ", selectedProgram.title);
20:21:43: this is the original list Array [
20:21:43: Object {
20:21:43: "description": "description",
20:21:43: "difficulty": "#FFDF00",
20:21:43: "id": "0e772ff0-c785-11e8-92f8-274c004a8b60",
20:21:43: "title": "Shrug",
20:21:43: "workouts": Array [
20:21:43: Object {
20:21:43: "description": "description",
20:21:43: "difficulty": "#FFDF00",
20:21:43: "id": "15618310-c785-11e8-92f8-274c004a8b60",
20:21:43: "title": "YouTube",
20:21:43: "workouts": Array [],
20:21:43: },
20:21:43: Object {
20:21:43: "description": "description",
20:21:43: "difficulty": "#d9534f",
20:21:43: "id": "189a18d0-c785-11e8-92f8-274c004a8b60",
20:21:43: "title": "Empty Title",
20:21:43: "workouts": Array [],
20:21:43: },
20:21:43: ],
20:21:43: },
20:21:43: Object {
20:21:43: "description": "Master",
20:21:43: "difficulty": "#FFDF00",
20:21:43: "id": "5e8860c0-cbe7-11e8-bca0-b7f8a21d1c09",
20:21:43: "title": "Red",
20:21:43: "workouts": Array [
20:21:43: Object {
20:21:43: "description": "It",
20:21:43: "difficulty": "#FFDF00",
20:21:43: "id": "e1ab31d0-cbf1-11e8-aaa1-3fb0ac98f560",
20:21:43: "title": "Redd",
20:21:43: "workouts": Array [],
20:21:43: },
20:21:43: Object {
20:21:43: "description": "World ",
20:21:43: "difficulty": "#FFDF00",
20:21:43: "id": "20cf8930-cc1d-11e8-8d7e-172d4a63fd8f",
20:21:43: "title": "Hello",
20:21:43: "workouts": Array [],
20:21:43: },
20:21:43: ],
20:21:43: },
20:21:43: ]
20:21:43: this is object: undefined
答案 0 :(得分:0)
Array.prototype.find
的工作方式略有不同。回调将为每个项目调用,并返回第一个为真的
var programList = [{id: "1"},{id:"2"}];
(( programList, programId ) => {
console.log(programId);
// find the correct programlist with same id as navId for mapping
const selectedProgram = programList.find(index => {
if (index.id === programId) {
console.log(programId, index.id);
return true;
}
return false;
});
console.log(selectedProgram);
})(programList, "2")