如何在React中获取当前状态?

时间:2017-04-17 17:59:26

标签: javascript reactjs

CODE:

getInitialState: function() {
        return {
           name: "",
           ingredients: "" 
        }
    },
handleSubmit: function() {
        var newRecipe = {
            name: this.state.name,
            ingredients: this.state.ingredients
        };
        this.props.handleAdd(newRecipe);
        this.handleClose();
    },
handleNameChange: function () {
        this.setState({
            name: event.target.value
        });
    },
    handleIngredientsChange: function () {
        this.setState({
            ingredients: event.target.value
        });
    },
render: function () {
    return (
        <div>
        <h3>Name</h3>
        <input value={this.state.name} onChange={this.handleNameChange}></input>
        <h3>Ingredients</h3>
        <textarea value={this.state.ingredients} onChange={this.handleIngredientsChange}></textarea>
        </div>
    )
}

状况:

this.state.nameundefined。为什么?

它必须与我当前的setState实现有关吗?

我正在学习React,所以可能会有一些明显的错误。

1 个答案:

答案 0 :(得分:4)

我认为eventhandleNameChange方法的问题缺少handleIngredientsChange个问题:

handleNameChange: function () {
  this.setState({
    name: event.target.value
  });
},

尝试将其更改为:

handleNameChange: function (event) {
  this.setState({
    name: event.target.value
  });
},

因为在您的初始方法中,event未定义,因此它也将您的状态设置为undefined

handleIngredientsChange也可以使用相同的内容,请将其更改为:

handleIngredientsChange: function (event) {
  this.setState({
    ingredients: event.target.value
  });
},