【问题标题】:React.js: Managing State and Component RerenderReact.js:管理状态和组件重新渲染
【发布时间】:2015-04-26 21:47:12
【问题描述】:

当我开始使用 React.js 冒险时,我碰壁了。我的以下时间跟踪应用的 UI 在多个级别上运行:

http://jsfiddle.net/technotarek/4n8n17tr/

效果如预期:

  1. 根据用户输入进行过滤
  2. 项目时钟可以独立启动和停止

什么不工作:

  1. 如果您启动一个或多个时钟然后尝试过滤,则任何不在过滤结果集中的时钟在重新显示后都会被重置。 (只需单击所有时钟上的开始,然后搜索项目,然后清除搜索输入。)

我假设发生这种情况是因为在过滤器输入的 onChange 上运行了 setState,它正在重新渲染所有内容并使用时钟 getInitialState 值。

那么,当过滤器重新渲染组件时,保留这些时钟和按钮的“状态”的正确方法是什么?我不应该将时钟或按钮“状态”存储为真正的 React 状态吗?我需要一个函数来在重新渲染之前显式保存时钟值吗?

我不要求任何人修复我的代码。相反,我希望能指出我对 React 的理解失败的地方。

为满足 SO 的代码要求,以下是包含时间跟踪器中每一行的组件。时钟通过 toggleClock 启动。 IncrementClock 写入被搜索过滤器清除的状态。请参阅上面小提琴链接中的完整代码。

var LogRow = React.createClass({

    getInitialState: function() {
        return {
            status: false,
            seconds: 0
        };
    },

    toggleButton: function(status) {
        this.setState({
            status: !this.state.status
        });
        this.toggleClock();
    },

    toggleClock: function() {
        var interval = '';
        if(this.state.status){
            // if clock is running, pause it.
            clearInterval(this.interval);
        } else {
            // otherwise, start it
            this.interval = setInterval(this.incrementClock, 1000);
        }
    },

    incrementClock: function() {
        this.setState({ seconds: this.state.seconds+1 });
    },

    render: function() {

        var clock = <LogClock seconds={this.state.seconds} />

        return (
            <div>
                <div className="row" key={this.props.id}>
                    <div className="col-xs-7"><h4>{this.props.project.title}</h4></div>
                    <div className="col-xs-2 text-right">{clock}</div>
                    <div className="col-xs-3 text-right"><TriggerButton status={this.state.status} toggleButton={this.toggleButton} /></div>
                </div>
                <hr />
            </div>
        );
    }
})

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

当您进行过滤时,您将从渲染输出中删除 LogRow 组件 - 当这种情况发生时,React 会卸载组件并释放其状态。当您随后更改过滤器并再次显示一行时,您将获得一个全新的LogRow 组件,因此再次调用getInitialState()

(这里也有泄漏,因为您没有清除使用 componentWillUnmount() 生命周期挂钩卸载这些组件的时间间隔 - 这些时间间隔仍在后台运行)

要解决这个问题,您可以将计时器状态以及控制和递增它的方法移出LogRow 组件,因此它的工作只是显示和控制当前状态,而不是拥有它。

您当前正在使用LogRow 组件将项目计时器的状态和行为联系在一起。您可以将此状态和行为管理移至以相同方式管理它的父组件,或者移至另一个对象,例如:

function Project(props) {
  this.id = props.id
  this.title = props.title

  this.ticking = false
  this.seconds = 0

  this._interval = null
}

Project.prototype.notifyChange = function() {
  if (this.onChange) {
    this.onChange()
  }
}

Project.prototype.tick = function() {
  this.seconds++
  this.notifyChange()
}

Project.prototype.toggleClock = function() {
  this.ticking = !this.ticking
  if (this.ticking) {
    this.startClock()
  }
  else {
    this.stopClock()
  }
  this.notifyChange()
}

Project.prototype.startClock = function() {
  if (this._interval == null) {
    this._interval = setInterval(this.tick.bind(this), 1000)
  }
}

Project.prototype.stopClock = function() {
  if (this._interval != null) {
    clearInterval(this._interval)
    this._interval = null
  }
}

由于使用的clearIntervals 是外部更改源,因此您需要以某种方式订阅它们,因此我实现了注册单个onChange 回调的功能,该回调LogRow 组件挂载在sn-p下面的时候是干什么的。

下面的工作代码 sn-p 做了最简单和最直接的事情来实现这一点,因此该解决方案有一些不鼓励的做法(修改道具)和警告(您只能在项目中拥有一个“听众”)但它有效。 (这通常是我对 React 的体验——它首先工作,然后你让它“正确”)。

接下来的步骤可能是:

  • PROJECTS 实际上是一个单例 Store - 您可以将其设为允许注册侦听器以更改项目状态的对象。然后,您可以添加一个 Action 对象来封装对项目状态的触发更改,因此 LogRow 永远不会直接触及其 project 属性,只会从中读取并侧向调用 Action 来更改它。 (这只是间接的,但有助于思考数据流)。请参阅 react-trainig 存储库中的 Less Simple Communication 示例,了解此示例。
  • 您可以让LogRow 在更高级别上侦听所有项目更改并在更改时重新渲染所有内容,从而使LogRow 完全变笨。将单个项目道具传递给 LowRow 将允许您实现 shouldComponentUpdate(),因此只有需要显示更改的行才会真正重新呈现。

<meta charset="UTF-8"> 
<script src="http://fb.me/react-with-addons-0.12.2.js"></script>
<script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<div class="container">
    <div class="row">
        <div id="worklog" class="col-md-12">
        </div>
    </div>
</div>
<script type="text/jsx;harmony=true">void function() { "use strict";

/* Convert seconds input to hh:mm:ss */
Number.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10);
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    var time    = hours+':'+minutes+':'+seconds;
    return time;
}

function Project(props) {
  this.id = props.id
  this.title = props.title

  this.ticking = false
  this.seconds = 0

  this._interval = null
}

Project.prototype.notifyChange = function() {
  if (typeof this.onChange == 'function') {
    this.onChange()
  }
}

Project.prototype.tick = function() {
  this.seconds++
  this.notifyChange()
}

Project.prototype.toggleClock = function() {
  this.ticking = !this.ticking
  if (this.ticking) {
    this.startClock()
  }
  else {
    this.stopClock()
  }
  this.notifyChange()
}

Project.prototype.startClock = function() {
  if (this._interval == null) {
    this._interval = setInterval(this.tick.bind(this), 1000)
  }
}

Project.prototype.stopClock = function() {
  if (this._interval != null) {
    clearInterval(this._interval)
    this._interval = null
  }
}

var PROJECTS = [
              new Project({id: "1", title: "Project ABC"}),
              new Project({id: "2", title: "Project XYZ"}),
              new Project({id: "3", title: "Project ACME"}),
              new Project({id: "4", title: "Project BB"}),
              new Project({id: "5", title: "Admin"})
            ];

var Worklog = React.createClass({

    getInitialState: function() {
        return {
            filterText: '',
        };
    },

    componentWillUnmount: function() {
        this.props.projects.forEach(function(project) {
          project.stopClock()
        })
    },

    handleSearch: function(filterText) {
        this.setState({
            filterText: filterText,
        });
    },

    render: function() {

        var propsSearchBar = {
            filterText: this.state.filterText,
            onSearch: this.handleSearch
        };

        var propsLogTable = {
            filterText: this.state.filterText,
            projects: this.props.projects
        }

        return (
            <div>
                <h2>Worklog</h2>
                <SearchBar {...propsSearchBar} />
                <LogTable {...propsLogTable} />
            </div>
        );
    }
});

var SearchBar = React.createClass({

    handleSearch: function() {
        this.props.onSearch(
            this.refs.filterTextInput.getDOMNode().value
        );
    },

    render: function() {

        return (
            <div className="form-group">
                <input type="text" className="form-control" placeholder="Search for a project..." value={this.props.filterText} onChange={this.handleSearch} ref="filterTextInput" />
            </div>
        );
    }

})

var LogTable = React.createClass({

    render: function() {

        var rows = [];
        this.props.projects.forEach(function(project) {

            if (project.title.toLowerCase().indexOf(this.props.filterText.toLowerCase()) === -1) {
                return;
            }
            rows.push(<LogRow key={project.id} project={project} />);
        }, this);

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

})

var LogRow = React.createClass({
  componentDidMount: function() {
    this.props.project.onChange = this.forceUpdate.bind(this)
  },

  componentWillUnmount: function() {
    this.props.project.onChange = null
  },

  onToggle: function() {
    this.props.project.toggleClock()
  },

  render: function() {
    return <div>
      <div className="row" key={this.props.id}>
        <div className="col-xs-7">
          <h4>{this.props.project.title}</h4>
        </div>
        <div className="col-xs-2 text-right">
          <LogClock seconds={this.props.project.seconds}/>
        </div>
        <div className="col-xs-3 text-right">
          <TriggerButton status={this.props.project.ticking} toggleButton={this.onToggle}/>
        </div>
      </div>
      <hr />
    </div>
  }
})

var LogClock = React.createClass({

    render: function() {

        return (
            <div>{this.props.seconds.toHHMMSS()}</div>
        );
    }
});

var TriggerButton = React.createClass({

    render: function() {

        var button;
          button = this.props.status != false
                    ? <button className="btn btn-warning" key={this.props.id} onClick={this.props.toggleButton}><i className="fa fa-pause"></i></button>
                    : <button className="btn btn-success" key={this.props.id} onClick={this.props.toggleButton}><i className="fa fa-play"></i></button>

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

    }

})

React.render(<Worklog projects={PROJECTS} />, document.getElementById("worklog"));

}()</script>

【讨论】:

  • 抱歉耽搁了,感谢您的回复。有些事情让我有点厌倦了通过使用外部对象来解决这个问题。试图弄清楚做事的“正确的 React 方式”是这个框架的最大挑战之一,因为文档相当稀缺。不过,我当然不能与您的最终结果争论。我将考虑您将行为管理提高一点的替代建议,这也是我认为@dhiraj-bodicherla 在他上面的评论中处理它的方式。我会尽快报告。
  • 我不认为总是有一种“正确的 React 方式”来做事。数据以及谁拥有和控制它,因为它是上下文相关的 - 例如如果此数据的唯一作用是在此列表中显示和使用,则在整个列表组件安装期间将存在的任何组件都可以轻松拥有该状态。但是,如果您在其他地方添加此信息的显示(例如,在某处的标题中添加一个小的“当前项目”计数器),这将成为一个不太可行的解决方案。
  • 这是香草js。这很好,但是违背了使用 react 及其生命周期方法的目的。
猜你喜欢
  • 1970-01-01
  • 2019-11-09
  • 2020-06-19
  • 2021-02-06
  • 1970-01-01
  • 2021-08-06
  • 2021-03-05
  • 1970-01-01
  • 2018-06-05
相关资源
最近更新 更多