CODE:
var RecipeBox = React.createClass({
getInitialState: function () {
return {
recipesArray: [],
adding: false,
editing: false,
currentIndex: 0
};
},
handleClick: function () {
this.setState({
adding: true
});
},
handleEditClick: function(index) {
this.setState({
editing: true,
currentIndex: index
});
},
handleClose: function() {
this.setState({
adding: false,
editing: false
});
},
handleAdd: function(newRecipe) {
this.setState({
recipesArray: this.state.recipesArray.concat(newRecipe)
});
console.log(this.state.recipesArray);
},
handleEdit: function(newRecipe, index) {
var newRecipesArray = this.state.recipesArray;
newRecipesArray[index-1] = newRecipe;
this.setState({
recipesArray: newRecipesArray
});
},
render: function() {
var i = 0;
var that = this;
var recipes = this.state.recipesArray.map(function(item) {
i++
that.handleEditClickSingle = that.handleEditClick.bind(this, i);
return (
<div className="table">
<Recipe key={i} name={item.name} ingredients={item.ingredients} />
<button key ={"edit"+i} onClick={that.handleEditClickSingle} className="btn edit btn-primary">Edit</button>
<button key ={"delete"+i} className="btn delete btn-danger">Delete</button>
</div>
);
});
return (
<div>
<h1>React.js Recipe Box</h1>
<button className="btn btn-primary" onClick={this.handleClick}>Add Recipe</button>
<table>
<tbody>
<tr>
<th>RECIPES</th>
</tr>
</tbody>
</table>
{recipes}
{ this.state.adding ? <AddRecipe handleClose={this.handleClose} handleAdd={this.handleAdd} /> : null }
{ this.state.editing ? <EditRecipe currentIndex = {this.state.currentIndex} handleClose={this.handleClose} handleEdit={this.handleEdit()}/> : null }
</div>
);
},
});
状况:
错误:
在现有状态转换期间(例如render
内)无法更新。渲染方法应该是道具和状态的纯函数。
我做错了什么?
问题的关键似乎在这里:
that.handleEditClickSingle = that.handleEditClick.bind(this,i);
答案 0 :(得分:0)
<强> SOLUTION:强>
var i = 0;
var that = this;
var recipes = this.state.recipesArray.map(function(item) {
i++
return (
<div className="table">
<Recipe key={i} name={item.name} ingredients={item.ingredients} />
<button key ={"edit"+i} onClick={() => { that.handleEditClick(i)}} className="btn edit btn-primary">Edit</button>
<button key ={"delete"+i} className="btn delete btn-danger">Delete</button>
</div>
);
});
答案 1 :(得分:-1)
我认为您的问题在于以下行中的render
方法
{ this.state.editing ? <EditRecipe currentIndex = {this.state.currentIndex} handleClose={this.handleClose} handleEdit={this.handleEdit()}/> : null }
将其替换为
{ this.state.editing ? <EditRecipe currentIndex = {this.state.currentIndex} handleClose={this.handleClose} handleEdit={this.handleEdit}/> : null }
您正在呼叫this.handleEdit
。相反,你应该像上面那样传递它。