【问题标题】:React renders text slower than style change - Alert componentReact 呈现文本比样式更改慢 - 警报组件
【发布时间】:2015-12-04 23:56:36
【问题描述】:

我正在学习反应。在下面的警报组件中,我正在更新一个简单的警报消息并将不透明度设置为 1,然后使用 CSS 过渡将其淡出。这是一个简单易用的应用程序,可以提高反应速度。

我遇到的问题是,当我更新警报文本this.props.message 时,在不透明度设置为 1 之后,上一条消息文本会显示几分之一秒,然后新消息才会替换它。它非常快,但似乎存在竞争条件,因为 DOM 或 React 呈现文本更改比样式更改慢。让我知道是否有一种方法可以在短信更改后省略打嗝并设置不透明度。谢谢。

var TodoApp = React.createClass({
    getInitialState: function() {
        return { 
            items: [],
            alert: { message: '', success: null }
        };
    }
    genericMethod: function() {
         ...
         this.setState({ alert: { message: message, success: true } });
         ...
    },
    ...
    render: function() {
        return (
            <div>
                <Alert message={this.state.alert.message} success={this.state.alert.success} />
                <ItemInput onItemSubmit={this.addItem} />
                <ItemList items={this.state.items} deleteItem={this.deleteItem} toggleComplete={this.toggleComplete} />
            </div>
        );
    }
});

...

var Alert = React.createClass({
    delayTime: 1000,
    getInitialState: function() {
        return {
            visible: false
        };
    },
    componentWillReceiveProps: function() {
        this.setState({ visible: true }, function() {
            this.setTimer();
        });
    },
    setTimer: function() {
        setTimeout(function(argument) {
            this.setState({ visible: false });
        }.bind(this), this.delayTime);
    },
    render: function() {
        var style = {
            opacity: (this.state.visible ? 1 : 0),
            transition: 'opacity '+(this.state.visible ? 0 : this.delayTime)+'ms'
        };
        var alertClass = 'alert'+(this.props.success ? ' success' : ' error');
        return (
            <div className={alertClass} style={style}>
                {this.props.message}
            </div>
        );
    }
});

【问题讨论】:

  • 这是一个 JSFiddle:jsfiddle.net/ojdemzLt 如果您无法复制您的问题,我可以尝试帮助您。
  • 我更新了小提琴,但如果不复制整个 todo 应用程序就无法重现该问题,这需要一个简单的 php 后端。不过,我确实缩小了范围。在我的顶级getInitialState 中,我正在设置一个包含待办事项和警报的对象:{ items: [ ], alert: { message: '', success: null } }。通过在警报上设置断点,我能够看到在设置新消息之前更改项目数组中的任何内容都会导致警报上的渲染周期。我将重新设计警报范围或设置警报的 ajax 回调。这很有帮助。谢谢。

标签: javascript css reactjs


【解决方案1】:

解决方案是从顶级 Todo 类中删除警报状态。所以{ items: [ ], alert: { message: '', success: null } } 变成了{ items: [ ] },然后使用&lt;Alert ref="alert" /&gt;this.refs['alert'].triggerAlert(message, true); 从我的Todo 组件调用子Alert 组件上的方法(如在这个SO 答案React.js - access to component methods 中看到的)而不是在componentWillReceiveProps 中观看警报组件。这样我就不会在每次添加或更新 Todo 项时设置新消息之前过早地渲染 Alert 组件。

【讨论】:

    猜你喜欢
    • 2015-08-17
    • 2020-09-04
    • 2021-08-10
    • 2019-11-23
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多