首页 > 解决方案 > 条件组件内的三元不会在道具更改时重新渲染

问题描述

父级有条件地渲染具有唯一道具的组件。接收这些道具的子渲染函数内部的三元组没有按预期工作。

我已经使用 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}and{this.state.underscore}被包装在h2标签中。否则,我希望将组件包装在p标签中。

标签: reactjsredux

解决方案


试试这个,这应该可以,这看起来也很整洁。

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苗条。


推荐阅读