2016-09-22 81 views
0

我正在使用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, 
    }; 
    }); 
+0

你能提供什麼state.doors數組看起來像?包括門對象屬性和值。你的'if(this.props.restaurant!== door.restaurant)'工作,因爲它不試圖訪問door.restaurant上的屬性,當它的undefined不起作用 – finalfreq

+0

無關你有沒有想過使用JSX傳播運算符,它會使JSX變得更容易閱讀;

+1

*「奇怪的是,這段代碼作爲一個完全匹配」*好吧,訪問未定義的屬性不是問題。嘗試訪問'undefined'屬性是。 'foo.bar'和'foo.bar.baz'有很大區別。 *「它看起來像door.restaurant被控制檯日誌爲未定義」*是的,這就是爲什麼錯誤也是如此。似乎你知道問題是什麼。你想從我們這裏得到什麼? –

回答

0

你的一個doors.restaurant爲null,這是什麼錯誤消息的狀態。空,不是未定義的。如果它沒有定義,那麼錯誤信息會這樣說。當你在這個值上調用doors.restaurant.indexOf時,它會返回一個錯誤。

當我輸入這個,你似乎已經知道了。

0

我認爲這個問題是您不使用===運算符,所以用==您要驗證只值不會打字。 例子:

var foo = null; 
 
var bar = ''; 
 
var baz = 0; 
 
var off = {}; 
 

 
console.log(bar == baz); // true 
 
console.log(bar === baz); // false 
 
console.log(foo == off.bar); // true 
 
console.log(foo === off.bar); // false

所以大概this.props.restaurant == door.restaurant是真的 但this.props.restaurant === door.restaurant是假