Title rewritten as: No matter what, I can't get a value from my array
P粉308783585
P粉308783585 2023-08-18 15:22:01
0
1
586
<p>I'm trying to display data from an array in my React component. </p> <p>I can see the data I need in the browser developer console via <code>console.log()</code>: </p> <pre class="brush:php;toolbar:false;">FinalRecords.js::recordTitle: (4) 0: {members: Array(10), id: 62, title: 'RR 1980 Record 1', storeId: 1088} 1: {members: Array(10), id: 63, title: 'RR 1980 Record 2', storeId: 1088} 2: {members: Array(10), id: 64, title: 'RR 1980 Record 3', storeId: 1088} 3: {members: Array(10), id: 65, title: 'RR 1980 Record 4', storeId: 1088} length: 4 [[Prototype]]: Array(0)</pre> <p>But I can't seem to figure out how to get the <code>title</code>. </p> <p>I've tried a lot of different things, this one being the most recent: </p> <pre class="brush:php;toolbar:false;">render() { const { recordId, records, bandName } = this.props; var data = records.filter((r) => r.id === recordId); var records = data.toArray(); console.log("FinalRecords.js :: recordTitle: ", records); return <div> record - {findRecordTitle(records, recordId) } - {bandName || ''} </div> } } function findRecordTitle(records, id) { return records.find((record) => { return record.id === id; }) }</pre> <p>I need to get the <code>title</code> of the record by using <code>id</code>. </p> <p>But it's always blank. </p> <p>Did I do something wrong? </p>
P粉308783585
P粉308783585

reply all(1)
P粉343408929

The name of this function means you expect it to return a "title" (which I would interpret as a string value):

function findRecordTitle(records, id) {
    return records.find((record) => {
        return record.id === id;
    })
}

However, nowhere in this function does it have anything to do with "title". It returns a matching object (or null) in the records array. If you just want to return the title property of the object, just return the property:

function findRecordTitle(records, id) {
    return records.find((record) => {
        return record.id === id;
    })?.title; // <--- 这里
}

EDIT: If your JavaScript environment is unable to use optional chaining, you can explicitly check for null before trying to use the object:

function findRecordTitle(records, id) {
    const record = records.find((record) => {
        return record.id === id;
    });
    return record ? record.title : null;
}

Or it can default to an empty string instead of null etc.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!