ReactJS-警告:组件正在更改要控制的文本类型的不受控制的输入

时间:2018-07-18 16:29:12

标签: javascript reactjs

我正试图摆脱此错误消息,但仍未成功。

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

也有指向Facebook页面的链接,但是我仍然不确定如何弄清这一点。

class EditItem extends Component {
    constructor(props) {
        super(props);
        this.state = {items: ''};

        this.addItemService = new ItemService();
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentDidMount(){
    axios.get('http://localhost:3005/items/edit/'+this.props.match.params.id)
    .then(response => {
      this.setState({ items: response.data });
    })
    .catch(function (error) {
      console.log(error);
    })
  }

  handleChange = (e) => {
    let items = Object.assign({}, this.state.items);    //creating copy of object
    items.item = e.target.value;                        //updating value
    this.setState({items});
  }

  handleSubmit(event) {
    event.preventDefault(); // not sure why this
    this.addItemService.updateData(this.state.items.item, this.props.match.params.id); // service for updating the data
    this.props.history.push('/index'); // redirect
  }

  render() {
    return (
          <div className="container">
            <form onSubmit={this.handleSubmit}>
              <label>
                Edit Item:
                <input type="text" value={this.state.items.item} className="form-control" onChange={this.handleChange}/>
              </label><br/>
              <input type="submit" value="Update" className="btn btn-primary"/>
            </form>
        </div>
    );
  }
}

在输入中似乎总是一个非空值,我该如何解决?

2 个答案:

答案 0 :(得分:11)

在状态项中被定义为字符串,因此当您将值分配给文本输入时,例如

<input type="text" value={this.state.items.item} className="form-control" onChange={this.handleChange}/>

您本质上是在写作

<input type="text" value={undefined} className="form-control" onChange={this.handleChange}/>

对于初始渲染,一旦API调用的结果可用并且项目状态更改为包含项目密钥的对象,您就将一个值传递给输入,因此将其从不受控制转换为受控,这就是警告即将。为了避免警告,您可以像这样

this.state = {items: { items: '' }};

或使用类似输入

<input type="text" value={this.state.items.item || ''} className="form-control" onChange={this.handleChange}/>

答案 1 :(得分:0)

当您尝试将未定义的值设置为任何输入类型时,这种警告主要发生在React中。您可以使用条件运算符来检查状态值是否未定义,如果未定义,则将其设置为空值。


<input type="text" value={this.state.items.item !== undefined ? this.state.items.item :  ''} className="form-control" onChange={this.handleChange}/>