2016-02-25 68 views
1

我正在嘗試使用Arkency的ReactJS Koans來學習React。我堅持練習05-Challenge-GroceryList-part-1.jsx。我的代碼在服務器上運行時會正確顯示列表,但是當我運行測試時,我會得到「1)應該有一個無序的雜貨列表...... AssertionError:GroceryItem應該只顯示< li>標籤內的文本。這個文本應該只包含雜貨商品名稱。「有任何想法嗎?如果沒有他們的意見,我的代碼如下:ReactJS Koans雜貨清單第1部分

var React = require("react"); 
class GroceryList extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     groceries: [ { name: "Apples" } ] 
    }; 
    } 

    render() { 
    for(var index = 0; index < this.state.groceries.length; index++) { 
     groceriesComponents.push(
      <GroceryListItem 
      grocery={this.state.groceries[index]} 
      /> 
    ); 
    } 

    return (
     <ul> 
     {groceriesComponents} 
     </ul> 
    ); 
    } 
} 

class GroceryListItem extends React.Component { 
    constructor(props) { 
    super(props); 
    } 

    render() { 
    return (
     <li key={this.props}> 
      {this.props} 
     </li> 
    ); 
    } 
} 

回答

1
class GroceryListItem extends React.Component { 
    constructor(props) { 
    super(props); 
    } 

    render() { 
    return (
     <li key={this.props}> 
      {this.props.grocery.name} 
     </li> 
    ); 
    } 
} 

嘗試。請注意,您使用的this.props不會打印雜貨的名稱......您必須參考prop。像上面一樣。

這一點代碼實際上是進入雜貨道具並抓取名稱值{this.props.grocery.name}

嘗試只添加名稱到雜貨店道具:

groceriesComponents.push(
      <GroceryListItem 
      grocery={this.state.groceries[index].name} 
      /> 
    ); 

然後在你的組件,你會怎麼做{this.props.grocery}對我來說,這聽起來像是一個驗證你的代碼,希望它看起來完全一樣孤單的程序。

+0

當我使用'{this.props.grocery.name}',我得到正確的值在瀏覽器中顯示,但測試套件仍然給我同樣的錯誤信息。如果你想看到它的測試套件,可以在https://github.com/neallred/reactjs_koans/tree/neredred – neallred

+0

@neallred - 嗯,這聽起來像它期待你寫完全一樣的代碼。看看我的編輯 – James111

+0

糟糕!你的第一個解決方案很好。我不小心編輯了一個臨時文件和你的結果,所以實際測試的文件沒有改變。它符合第一條建議。謝謝! – neallred