子组件不使用shouldComponentUpdate重新呈现

时间:2019-04-09 05:02:04

标签: reactjs react-lifecycle

更改其prop时,我的子组件也会更改其状态。我想重新渲染子组件ImageSlide,以便在状态更改时调用其他字符串。 className进行了很好的更改,控制台很好地显示了更改后的值。但是它不会重新渲染视图。

我尝试了shouldComponentUpdate,但没有成功。 如何重新渲染ImageSlide?

let languages = {
    en: require('textEnglish'),
    kr: require('textKorean')
}

class ImageSlide extends Component {

constructor(props) {
    super(props);
    this.state={
        lang: this.props.lang,
        url: this.props.url
    }
}

languageSelect=()=> {
    if (this.state.lang === 'kr') {
        return 'kr';
    } else {
        return 'en';
    }   
}

static getDerivedStateFromProps(nextProps, prevState){
    if (nextProps.lang !== prevState.lang |
        nextProps.url !== prevState.url )
    {
        return  {lang : nextProps.lang, url: nextProps.url} ;
    }
}


shouldComponentUpdate(nextProps, nextState){
    return true;
 //I tried also:
 // if (nextProps.url !== this.state.url |
 // nextProps.lang !== this.state.lang)
 //     return true;
}

render() {
    const Text=languages[this.languageSelect()];
    return (    
        <div className="test-transition">
            {console.log(this.state.lang)}
            {console.log(this.state.url)}
            {console.log(Text["p1_3_"+String(this.state.url)])}
            <div className={`pic${this.state.url}`}>
                {Text["p1_3_"+String(this.state.url)]}              
            </div>
        </div>      
    );
}

}

1 个答案:

答案 0 :(得分:0)

使用componentDidUpdateshouldComponentUpdate之类的任何生命周期事件来检查新道具是否已更改,或者您也可以尝试componentWillReceiveProps(不推荐使用,因为不推荐使用)

componentDidUpdate()
    {
    /*Check for prev props condition*/
    this.forceUpdate(); /*this method renders the component*/
    }
相关问题