相关疑难解决方法(0)

ReactJS - 在调用"setState"的任何时候都会调用render吗?

React是否每次都会重新渲染所有组件和子组件setState

如果是这样,为什么?我认为这个想法是React只在需要的时候渲染 - 当状态改变时.

在下面的简单示例中,两个类在单击文本时再次呈现,尽管状态在后续单击时不会更改,因为onClick处理程序始终将其state设置为相同的值:

this.setState({'test':'me'});
Run Code Online (Sandbox Code Playgroud)

我希望渲染只会在state数据发生变化时发生.

以下是该示例的代码,作为JS Fiddle和嵌入式代码段:

var TimeInChild = React.createClass({
    render: function() {
        var t = new Date().getTime();

        return (
            <p>Time in child:{t}</p>
        );
    }
});

var Main = React.createClass({
    onTest: function() {
        this.setState({'test':'me'});
    },

    render: function() {
        var currentTime = new Date().getTime();

        return (
            <div onClick={this.onTest}>
            <p>Time in main:{currentTime}</p>
            <p>Click me to update time</p>
            <TimeInChild/>
            </div>
        );
    }
});

ReactDOM.render(<Main/>, document.body);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

[1]: http://jsfiddle.net/fp2tncmb/2/
Run Code Online (Sandbox Code Playgroud)

javascript reactjs

445
推荐指数
7
解决办法
21万
查看次数

React shouldComponentUpdate()= false不停止重新渲染

基本上,我有这个非常简单的反应组件.它的作用是环绕'react-intercom',只有在状态发生变化时才会渲染它.为了简化问题,我已经将该shouldCompoenentUpdate()方法硬连接以始终返回false.

    import React from 'react';
    import Intercom from 'react-intercom';
    
    class IntercomWrapper extends React.Component {
        shouldComponentUpdate(nextProps, nextState) {
            // console.log(!!nextProps.user && nextProps.user.userId !== this.props.user.userId);
            // return !!nextProps.user && nextProps.user.userId !== this.props.user.userId;
            return false;
        }
    
        render() {
            console.log('rendering');
            return <Intercom {...this.props} />;
        }
    };
    
    export default IntercomWrapper;
Run Code Online (Sandbox Code Playgroud)

会发生什么事情,它总是会重新渲染,这不应该发生.

任何人都知道为什么会发生这种情况?

javascript reactjs

13
推荐指数
1
解决办法
7532
查看次数

标签 统计

javascript ×2

reactjs ×2