道具变更时,三元内部条件组件不会重新渲染

时间:2019-02-15 06:01:29

标签: reactjs redux

父母有条件地渲染具有唯一道具的组件。接收这些道具的孩子的渲染功能中的三元函数无法正常工作。

我已经使用componentWillRecieveProps来设置状态,并尝试让三元基于状态。并且,经过研究,我将代码更改为使用getDerivedStateFromProps函数(因为componentWillRecieveProps被认为是不安全的?)代码如下。

另外,我知道该组件正确接收了道具,并且状态正在更新为正确的值(由于console.logs);

class AppearTyping extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        underscore: '',
        header: true
    }
}

.
.
.

static getDerivedStateFromProps(props, currentState) {
    if (currentState.header !== props.header) {
        return {
            header: props.header,
        }
    }
    return null
}


render() {
    let display = this.props.paragraph.join('');
    console.log(this.state.header);
    return (
        <div>
            {this.state.header ? <h2 className="about white">{display} 
{this.state.underscore}</h2> : <p className="about white">{display}</p>}
        </div>
    )
}
}    

如果组件接收到prop:header = true,我希望将{display}和{this.state.underscore}包裹在h2标签中。否则,我希望将该组件包装在p标签中。

2 个答案:

答案 0 :(得分:0)

尝试一下,这应该可以工作,而且看起来也干净整洁。

render(){
 let display = this.props.paragraph.join('');
 console.log(this.state.header);
 const content = this.state.header ? 
              <h2 className="about white">
                   {display} 
                   {this.state.underscore}
              </h2> : 
               <p className="about white">
                   {display}
               </p>;
  return <div>
            {content}
         </div>;
}

尝试使您的return保持苗条。

答案 1 :(得分:0)

在没有实际看到父母如何使用AppearTyping组件的代码的情况下,还不清楚您看到的是什么意外行为,但是,我能够获得render方法使用状态的三元条件在h2p之间切换。

我的render方法如下:

render () {
  let display = this.props.paragraph.join('')
  console.log(this.state.header)
  return (
    <div>
      {this.state.header ?
       <h2 className='about white'>{display} {this.state.underscore}</h2> :
       <p className='about white'>{display}</p> }
    </div>
  )
}

这里是一个codesandbox,显示了正在执行的代码

顺便说一句,由于您主要是打开要使用的 组件(h2p),所以您是否知道也可以有条件地选择该组件基于状态?这将帮助您删除一些重复的代码。

render () {
  let display = this.props.paragraph.join('')
  console.log(this.state.header)
  const WrapperComponent = this.state.header ? 'h2' : 'p'
  return (
    <div>
      <WrapperComponent className='about white'>
        {display}
        {this.state.header ? this.state.underscore : null }
      </WrapperComponent>
    </div>)
}