【问题标题】:React: Warning: setState(...): Cannot update during an existing state transition反应:警告:setState(...):在现有状态转换期间无法更新
【发布时间】:2016-12-13 03:42:18
【问题描述】:

当我尝试插入新的配方元素时,我的项目不断崩溃。我使用RecipeList 中的this.state.recipes.map... 能够根据需要更新配方(例如删除、编辑等)。删除功能有效,但我无法添加新的配方元素。
如果我将语句切换到this.props.recipes.map...,我可以毫无问题地插入元素,但无法删除,因为删除会触发状态更改,并且需要状态更改来反映更新而不是道具。有人对这个问题有任何提示吗?谢谢!

食谱列表:

var RecipeList = React.createClass({
getInitialState: function(){
    return {recipes: []};
},
deleteRecipe: function(recipe){
    var curRecipes = this.state.recipes.slice('');
    curRecipes.splice(recipe.recipeKey,1);
    this.setState({recipes: curRecipes});
},
componentWillMount: function(){
    this.setState({recipes: this.props.recipes});
},
render: function(){

    var recipeNodes = this.state.recipes.map(function(recipe,index){
        return <Recipe onDelete={this.deleteRecipe} recipeKey={index} key={index} recipeTitle={recipe.recipeTitle} ingredients={recipe.ingredients}  instructions={recipe.instructions} />
    },this);
    return(
        <div>
            {recipeNodes}
        </div>
    );
}
});

配方容器:

var RecipeBox = React.createClass({
getInitialState: function(){
    return {showForm: false,
            recipes: []
        };
},
openForm: function(){
    this.setState({showForm: true});
},
handleRecipeSubmit: function(recipe){
    var curRecipes = this.state.recipes.slice('');
    curRecipes.push({recipeTitle: recipe.recipeTitle,ingredients: recipe.ingredients, instructions: recipe.instructions});
    this.setState({recipes: curRecipes});
},
render: function(){
    return(
        <div id="recipeBox">
            <RecipeList recipes={this.state.recipes} />
            <div className="recipeButtons">
                <button id="addRecipeButton" className="btn-style" onClick={this.openForm}>Add Recipe</button>
            </div>
            {this.state.showForm ? this.refs.dialogWithCallBacks.show() : null}
            <SkyLight
                dialogStyles={formDialog}
                ref="dialogWithCallBacks"
                title="Add Recipe">
                <RecipeForm onRecipeSubmit={this.handleRecipeSubmit} skylightRef={this.refs.dialogWithCallBacks} />
            </SkyLight>
        </div>
    );
}
});

配方表:

var RecipeForm = React.createClass({
getInitialState: function(){
    return {hideDialog: false};
},
getFormData: function(){
    var ingredients= document.getElementsByClassName("ingredient"),
        recipeName = document.getElementsByName('recipeName')[0].value,
        instructions = document.querySelector('textarea').value,
        data = [];

    ingredients = [].slice.call(ingredients).map(function(ingredient,index){
        return {
            "quantity": ingredient.childNodes[0].value,
            "ingredient": ingredient.childNodes[1].value,
            "unit": ingredient.childNodes[2].value
        };
    });

    // Combine results into output array
    data.push(recipeName);
    data.push(ingredients);
    data.push(instructions);

    return data;
},
submitRecipe: function(event){
    event.preventDefault();
    var data = this.getFormData();

    // Hide the SkyLight modal container
    this.setState({hideDialog: true});

    // Submit form
    this.props.onRecipeSubmit({recipeTitle: data[0], ingredients: data[1], instructions: data[2]});
},
render: function(){

    return(
        <form onSubmit={this.submitRecipe}>
            <section className="recipe-main">
                <h2 style={{'border-bottom': 'none'}}>Recipe Name</h2>
                <RecipeFormName />
                <h2 style={{'border-bottom': 'none'}}>Ingredients</h2>
                <RecipeFormIngredients />
            </section>
            <RecipeFormInstructions />
            <input type="submit" value="Add Recipe" />
            {this.state.hideDialog ? this.props.skylightRef.hide() : null}
        </form>
    )
}
});

【问题讨论】:

  • 你不应该像这样使用 DOM 和 react:document.getElementsByClassName(在你的 getFormData 中)。查看文档:facebook.github.io/react/docs/forms.html
  • 谢谢。删除了document.getElementsByClassName 并重组了我获取表单数据的方式,但它仍然给了我同样的错误。

标签: javascript reactjs setstate


【解决方案1】:

您应该将 componentWillMount 中的代码移动到 getInitialState。

getInitialState: function(){
    return {recipes: this.props.recipes};
},

【讨论】:

  • 我试过了,但仍然遇到同样的错误。找不到错误提到的状态转换发生在哪里。
【解决方案2】:

需要将RecipeList组件改为

&lt;RecipeList recipes={this.state.recipes} onChange={this.handleChange}/&gt;

然后从RecipeBox 而不是直接在RecipeList 中处理删除更改。必须使用 this.props.map... 来显示新食谱并删除可见的。

var RecipeList = React.createClass({
    getInitialState: function(){
        return {recipes: this.props.recipes};
    },
    deleteRecipe: function(recipe){
        var curRecipes = this.props.recipes.slice('');
        curRecipes.splice(recipe.recipeKey,1);
        this.props.onChange({recipes: curRecipes});
    },
    render: function(){

        var recipeNodes = this.props.recipes.map(function(recipe,index){
            return <Recipe onDelete={this.deleteRecipe} recipeKey={index} key={index} recipeName={recipe.recipeName} ingredients={recipe.ingredients}      instructions={recipe.instructions} />
        },this);

        return(
            <div>
                {recipeNodes}
            </div>
        );
    }
});

【讨论】:

    猜你喜欢
    • 2017-12-20
    • 2017-05-16
    • 2016-09-20
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    相关资源
    最近更新 更多