首页 > React 中这种数据流是否是不必要的?

React 中这种数据流是否是不必要的?

在比较专业的代码中看到类似这样的写法:

var Input = React.createClass({
  getInitialState: function() {
    return {value: 'Hello!'};
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function () {
    var value = this.state.value;
    return (
      <div>
        <input type="text" value={value} onChange={this.handleChange} />
      </div>
    );
  }
});

ReactDOM.render(<Input/>, document.body);

文本中的输入值,通过state,又显示在文本框中,这样做是否多余?因为文本框中的value值不用state告诉它,它自己就知道啊。
如果input的值只在编辑文本框时改变,并不受其它逻辑控制而改变,并不需要写value={value}啊。

var Input = React.createClass({
  getInitialState: function() {
    return {value: 'Hello!'};
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function () {
    return (
      <div>
        <input type="text" onChange={this.handleChange}/>
      </div>
    );
  }
});

ReactDOM.render(<Input/>, document.body);
ReactDOM.render(<Input/>, document.body);

我对一个开源项目进行了pr,去掉了项目中我认为多余的数据流,然后开发者这样回复我,他回答了我的疑问:

Thanks, but the state is there for a reason. It's the fundamental
distinction between an uncontrolled component and a controlled one (more info here). The latter is preferred whenever possible.

There's no duplication of source of truth here, in case that's your worry. The input's text is completely determined by the value we pass to it. Essentially we've lifted the source of truth from the DOM into a platform-agnostic state value.


这两种方式的取值方式不同,第一种的取值通过this.state.value,第二种取值需要通过 this.refs的方式取

【热门文章】
【热门文章】