React JS状态不会在点击时更新

时间:2016-09-12 11:43:48

标签: javascript reactjs

我的陈列室组件如下:

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函数,我更新状态,并且我从showroom组件调用一个函数来更新状态。

根据该状态,我改变了显示内容的方式。

但问题是,当第一次调用函数setListView时,状态不会变为false。当我第二次调用setListView时,它会将状态设置为false。

this.props.handleChangeView函数是一个回调函数,应该在状态更新后调用它。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

setState中的第二个参数应为function

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

在您的示例中,您将结果从setState

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

handleChangeView不返回任何内容,这意味着您传递给setState undefined

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

所以你不能在handleChangeView

之后致电setState