小编典典

ReactJS状态与属性

reactjs

这可能会在负责任和有见识之间走出一条界限,但是我将反复讨论如何随着复杂性的增加和使用某些方向来构建ReactJS组件。

来自AngularJS,我想将模型作为属性传递到组件中,并让组件直接修改模型。
还是应该将模型拆分为各种state属性,并在向上游发送回时将其重新编译在一起?什么是ReactJS方式?

以博客文章编辑器为例。尝试直接修改模型最终看起来像:

var PostEditor = React.createClass({
  updateText: function(e) {
    var text = e.target.value;
    this.props.post.text = text;
    this.forceUpdate();
  },
  render: function() {
    return (
      <input value={this.props.post.text} onChange={this.updateText}/>
      <button onClick={this.props.post.save}/>Save</button>
    );
  }
});

好像错了

是否更像React的方式来制作text模型属性state,并在保存之前将其编译回模型中:

var PostEditor = React.createClass({
  getInitialState: function() {
    return {
      text: ""
    };
  },
  componentWillMount: function() {
    this.setState({
      text: this.props.post.text
    });
  },
  updateText: function(e) {
    this.setState({
      text: e.target.value
    });
  },
  savePost: function() {
    this.props.post.text = this.state.text;
    this.props.post.save();
  },
  render: function() {
    return (
      <input value={this.state.text} onChange={this.updateText}/>
      <button onClick={this.savePost}/>Save</button>
    );
  }
});

不需要调用this.forceUpdate(),但是随着模型的增长,(帖子可能会有作者,主题,标签,评论,评分等),该组件开始变得非常复杂。

使用ReactLink的第一种方法是可行的吗?


阅读 233

收藏
2020-07-22

共1个答案

小编典典

您的第二种方法更像是它。React并不关心模型,而是关心
以及它们在应用程序中的流动方式。理想情况下,您的帖子模型应存储在根目录下的单个组件中。然后创建子组件,每个子组件都使用模型的各个部分。

您可以将回调传递给需要修改数据的子级,然后从子级组件中调用它们。

直接修改this.props或this.state并不是一个好主意,因为React无法接受更改。这是因为React对您的发布道具进行了浅层比较,以确定它是否已更改。

我做了这个jsfiddle来展示数据如何从外部组件流到内部组件。

handleClick方法显示了3种(不正确)更新状态的方法:

var Outer = React.createClass({

  getInitialState: function() {
    return {data: {value: 'at first, it works'}};
  },

  handleClick: function () {

    // 1. This doesn't work, render is not triggered.
    // Never set state directly because the updated values
    // can still be read, which can lead to unexpected behavior.

    this.state.data.value = 'but React will never know!';

    // 2. This works, because we use setState

    var newData = {value: 'it works 2'};
    this.setState({data: newData});

    // 3. Alternatively you can use React's immutability helpers
    // to update more complex models.
    // Read more: http://facebook.github.io/react/docs/update.html

    var newState = React.addons.update(this.state, {
      data: {value: {$set: 'it works'}}
    });
    this.setState(newState);
 },

  render: function() {
      return <Inner data={this.state.data} handleClick={this.handleClick} />;
  }
});
2020-07-22