2016-11-11 95 views
0

以我反应-Redux的应用,我有以下呈现compoent反应组分:终极版:基于条件

render(){ 

     return(<div style={this.setStyler()} > 
        {this.props.value} 
      </div>); 
    } 

setStyler()的操纵一个减速器,并返回其应css被应用的值。

的问题是,我面对的错误:

Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount. 

看来,终极版不允许我根据状态条件下呈现组件。但我不知道我该如何解决这个问题?

更新

setStyler(){ 
    if(this.props.activeWord!=this.props.wordId) 
     return { color:'black', fontWeight: 'normal' }; 
    if(this.props.letterId>this.props.activeLetter && this.props.activeWord==this.props.wordId) 
     return { color:'black', fontWeight: 'normal' }; 

    if(this.props.letterId==this.props.activeLetter && this.props.activeWord==this.props.wordId){ 
      if(this.props.value==this.props.newTypedLetter){ 
       this.props.color({ color:'green', fontWeight: 'bold' }); //change reducer 
       return { color:'green', fontWeight: 'bold' }; 
      } 
      if(this.props.value!=this.props.newTypedLetter){ 
       this.props.color({ color:'red', fontWeight: 'bold' });  ////change reducer 
       return { color:'red', fontWeight: 'bold' }; 
       } 

    } 
    if(this.props.letterId<this.props.activeLetter && this.props.activeWord==this.props.wordId) 
      return this.props.letterColor; 

    } 
+0

帮助提供的信息很困难。添加setStyler()功能代码 –

+0

您提供的代码不会导致您看到的错误。你还在哪里使用setState()? –

回答

1

我要说的是,在这种情况下,你应该尝试调用this.setStyler()constructorcomponentWillUpdate。然后,您只需从render函数中读取来自redux商店的价值。

这应该做的工作,但仍然不是最好的方法国际海事组织,因为你正在使你的组件fat。您可以尝试阅读关于Presentational and Container Components的这篇文章,这将解释设计您的组件的模式。

问题是,你正试图修改渲染函数,这是一个side effect。函数式编程范式中的反应试图遵循,这是一种反模式。正如你所看到的,反应试图通过你收到的错误来确切地告诉你。

+0

看来,你是对的。我试图为它设置一个compoent状态,但仍然有问题 –