我正在使用React構建餐館違規應用程序,並且我試圖返回搜索到的術語是數據集的子字符串的結果。但是,我收到一條錯誤消息:JS查找IndexOf()字符串中的子字符串
ViolationsRequest.jsx:49 Uncaught TypeError: Cannot read property 'indexOf' of null.
基於我的測試,它看起來像door.restaurant被控制檯日誌爲未定義。奇怪的是,這段代碼完全匹配,即,如果將if塊切換爲:
if (this.props.restaurant == door.restaurant) {
這是我的代碼塊。
const violationElements = this.state.doors.map((door, idx) => {
if (door.restaurant.indexOf(this.props.restaurant) !== -1) {
console.log();
return (
<ViolationsView key={idx}
restaurant={door.restaurant}
building={door.building}
street={door.street}
zip={door.zip}
phone={door.phone}
cuisine={door.cuisine}
inspectionDate={door.inspectionDate}
action={door.action}
violationCode={door.violationCode}
violationDescription={door.violationDescription}
criticalFlag={door.criticalFlag}
score={door.score}
grade={door.grade}
gradeDate={door.gradeDate}
inspectionType={door.inspectionType}
/>
)
}
});
這是我state.doors數組:
const cleanData = restaurantData.data.map((inspectionData) => {
const [sid, id, position, createdAt, createdMeta,
updatedAt, updatedMeta, meta, camis, dba, boro,
building, street, zipcode, phone, cuisine,
inspectionDate, action, violationCode,
violationDescription, criticalFlag, score, grade,
gradeDate, recordDate, inspectionType] = inspectionData;
return {
sid: sid,
restaurant: dba,
building: building,
street: street,
zip: zipcode,
phone: phone,
cuisine: cuisine,
inspectionDate: inspectionDate,
action: action,
violationCode: violationCode,
violationDescription: violationDescription,
criticalFlag: criticalFlag,
score: score,
grade: grade,
gradeDate: gradeDate,
inspectionType: inspectionType,
};
});
你能提供什麼state.doors數組看起來像?包括門對象屬性和值。你的'if(this.props.restaurant!== door.restaurant)'工作,因爲它不試圖訪問door.restaurant上的屬性,當它的undefined不起作用 – finalfreq
無關你有沒有想過使用JSX傳播運算符,它會使JSX變得更容易閱讀; –
*「奇怪的是,這段代碼作爲一個完全匹配」*好吧,訪問未定義的屬性不是問題。嘗試訪問'undefined'屬性是。 'foo.bar'和'foo.bar.baz'有很大區別。 *「它看起來像door.restaurant被控制檯日誌爲未定義」*是的,這就是爲什麼錯誤也是如此。似乎你知道問題是什麼。你想從我們這裏得到什麼? –