反应组件渲染不正确

时间:2017-07-31 01:36:40

标签: javascript reactjs

我有一个反应项目,一个食谱盒,其中包括打开食谱和添加/删除成分的功能。这是a fiddle。您可以单击配方名称以打开配方。有一个编辑按钮,显示删除按钮,并提供更改成分名称的选项。当删除成分时#39;按下按钮,无论选择哪种成分,最后一种成分似乎总是被删除,但是当“完成”按钮时,单击按钮,可编辑的输入框变回文本,显示正确的更改,删除正确的成分并保留最后一个成分。虽然这在功能上有效,但它显然不是非常友好的UI,我想知道为什么会这样。任何帮助都会很棒。

jsFiddle

class Input extends React.Component {
  render() {
   const array = this.props.update;
   let booleanButton = null;
   if (this.props.ingr) {
////////////////////////////
// here is the button's JSX
    booleanButton = <button onClick=
    {this.props.handleDeleteIngredient.bind(this, array)}>delete 
    ingredient</button>;
///////////////////////////
   }
 return (<div><form><input type="text" defaultValue={this.props.text} 
   onChange={this.props.onChange.bind(this, array)} /></form>{booleanButton}
  </div>)
  }
}

处理程序:

handleDeleteIngredient(data, e ) {
  var key = data[2];
  var ingrs = this.state.ingrs;
  ingrs.splice(key, 1);
  this.setState({ingrs:ingrs});
}

1 个答案:

答案 0 :(得分:2)

您的描述很安静,根据您的小提琴代码,我认为您的问题是由于没有为您的列表项目设置好的密钥造成的。
从它在这一行中看起来,你没有一个键= {ingrs [i]}道具,尝试将它设置为id看它会起作用,但是将关键词命名为关键可能不是一个好主意,试着给实际的身份证。

ingrList.push(<Input key={ingrs[i]} handleDeleteIngredient={this.handleDeleteIngredient.bind(this)} id={id}  update={[this.props.objectIndex, "ingrs", i]} onChange={this.onInputChangeIng.bind(this)} text={ingrs[i]} />);