簡體   English   中英

點擊時React JS狀態不會更新

[英]React JS state doesn't update on click

我的陳列室組件如下:

export default class Showrooms extends React.Component {
constructor(props){
    super(props);

    this.state = {
        blockView: true
    };
}

handleChangeView(view){
    console.log(view);
    this.setState({blockView: view});
}

render(){
    const language = this.props.language;
    return (
        <div className="col-lg-10 col-md-9 col-sm-9 col-xs-12 text-center">
            <div className="lists">
                <div className="listsTitle">{language.portal.introPageTitle}</div>

                <ViewBar handleChangeView={this.handleChangeView.bind(this)}/>

                <div className="allLists">
                    <div className="view">

                        {this.props.allLists.map( (list, i) =>  <View key={i} list={list} language={language} blockView={this.state.blockView}/>)}

                        <div className="clearfix"/>
                    </div>
                </div>
                <div className="clearfix"/>

            </div>
        </div>
    );
}
}

和我的viewBar組件如下:

export default class ViewBar extends React.Component {
constructor(props){
    super(props);
    this.state = {
        blockView: true
    };
}

setBlockView(event){
    event.preventDefault();
    this.setState({blockView: true}, this.props.handleChangeView(this.state.blockView));
}

setListView(event){
    event.preventDefault();
    this.setState({blockView: false}, this.props.handleChangeView(this.state.blockView));
}


render(){
    let blockViewAddBorder = this.state.blockView ? "activeView" : "";
    let listViewAddBorder = !this.state.blockView ? "activeView" : "";
    return (
        <div className="viewBar">
            <Link to="" onClick={this.setListView.bind(this)} className={`listViewIcon ${listViewAddBorder}`}>
                <FontAwesome name="list" className="portalFaIcon"/>
            </Link>
            <Link to="" onClick={this.setBlockView.bind(this)} className={blockViewAddBorder}>
                <FontAwesome name="th-large" className="portalFaIcon"/>
            </Link>
        </div>
    )
}
}

在viewBar組件中,我有兩個onClick函數,它們在其中更新狀態,並從顯示組件中調用一個函數以更新狀態。

根據狀態,我可以更改顯示內容的方式。

但是問題是,第一次調用setListView函數時,狀態不會更改為false。 當我第二次調用setListView時,它將狀態設置為false。

this.props.handleChangeView函數是一個回調函數,應在狀態更新后調用它。

有什么建議嗎?

setState第二個參數應為function

this.setState({ blockView: true }, () => {
   this.props.handleChangeView(this.state.blockView);
}) 

在您的示例中,您將結果從handleChangeView傳遞給setState

this.setState({
  blockView: true
}, this.props.handleChangeView(this.state.blockView));

handleChangeView返回任何內容,這意味着您將undefined傳遞給setState

this.setState({
  blockView: true
}, undefined);

所以你不要在setState之后調用handleChangeView

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM