2016-02-25 51 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