【问题标题】:React.js Component Re-renderReact.js 组件重新渲染
【发布时间】:2018-06-23 06:09:51
【问题描述】:

除了this.setStatethis.forceUpdate 方法之外,还有其他方法或事件会触发组件从自身内部重新渲染吗?

我是从react-redux 的角度提出这个问题的,我读到的这个问题是this.forceUpdate。我还读到React.js 不鼓励使用这种方法。这就是我好奇的原因。我希望我没有误解或被我的信息来源误导。

【问题讨论】:

    标签: javascript reactjs ecmascript-5


    【解决方案1】:
    const mapStateToProps = state => {
      return {
        objects: state.objectIds.map(id => state.objects[id])
      }
    }
    


    这个方法在传递给connect时,

    export default connect(
      mapStateToProps,
      mapDispatchToProps
    )(TodoList)`
    



    redux 会提供新的 props,必须在 "component will receive new props" 中捕获,这会进一步调用 render 方法。

    【讨论】:

    • 这个是对的,如果我们将redux映射到组件的props,那么就会调用render。
    【解决方案2】:

    您可以使用 shouldComponentUpdate 生命周期方法来实现:

    shouldComponentUpdate(nextProps, nextState){
    
        //Compare the nextProps and nextState with current props or state respectively if it matters,then :
        //If returned true, the component will re-render if it's false there will 
        //be no change
    
        return true;  
    
    }
    

    【讨论】:

    • 这是完全错误的,这个生命周期的方法是有条件地阻止渲染,而不是OP问什么