setState不会更改视图

时间:2018-03-20 09:13:48

标签: javascript reactjs redux

我有一个组件" BulkActionPanel"这会呈现一些按钮。根据数组属性启用或禁用按钮" selectedJobIds"从其父组件" Grid"作为道具传递。确切地说,如果道具的长度" selectedJobIds"大于0然后启用按钮,否则禁用它们。

我在" onClick" BulkActionPanel组件中的所有按钮,将selectedJobIds设置为' 0'通过调用actionCreator" this.props.removeSelectedJobIds([rowData.id])"并确保按钮被禁用。

由于动作创建者需要花费大量时间(在网格上进行大量处理),因此我维持一个本地状态"禁用"在BulkActionPanel内部,确保首先禁用按钮,然后在redux存储中更新selectedJobIds状态。

我编写了下面的代码,但按钮不会被禁用,直到动作创建者" this.props.removeSelectedJobIds([rowData.id]);"饰面。

export default class Grid extends Component {
     render() {
         <BulkActionPanel
              actions={this.bulkActions}
              selectedJobIds={this.getFromConfig(this.props.config, [SELECTED_ROWS_PATH_IN_GRID_CONFIG])}
         />
         <SlickGrid/>
     }
}


export default class BulkActionPanel extends Component {

    constructor() {
        super();
        this.state = {
            disable: true
        }
    }

    componentWillReceiveProps(nextProps){
        if(nextProps.selectedJobIds && nextProps.selectedJobIds.length > 0){
            this.setState({disable:false});
        }
    }

    shouldComponentUpdate(nextProps) {
        return nextProps.selectedJobIds !== undefined && nextProps.selectedJobIds.length
    }

    @autobind
    onActionButtonClick(action) {
            this.setState({disable:true}
            , () => {
                    // Action creator that takes a lots of time
                    this.props.removeSelectedJobIds([rowData.id]);

                }
            );
    }

    @autobind
    renderFrequentActions() {
        return this.props.actions.frequentActions.map((frequentAction) => (
            <button
              className="btn btn-default"
              key={frequentAction.DISPLAY_NAME}
              onClick={() => this.onActionButtonClick(frequentAction)}
              disabled={this.state.disable}
            >
                {frequentAction.DISPLAY_NAME}
            </button>
            ));
    }

    render() {
        const frequentActions = this.renderFrequentActions();

        return (
            <div className="btn-toolbar bulk-action-panel">
                {frequentActions}
            </div>
        );
    }
}

是否与Grid和BulkActionPanel组件的父子关系有关?这里的潜在客户表示赞赏。

谢谢!

2 个答案:

答案 0 :(得分:-1)

我认为你的组件没有通过这个

if(nextProps.selectedJobIds && nextProps.selectedJobIds.length > 0){
    this.setState({disable:false});
}

你的componentWillReceiveProps

答案 1 :(得分:-1)

如果未触发来自removeSelectedJobIds的回调,则不会更改状态,尝试设置按钮状态,并在removeSelectedJobIds完成时使用reducer调度操作,捕获该操作并重新呈现或更改所需内容。< / p>

OR

将减速机用于一切。 onclick调用actin类型,让你知道表中的数据是渲染,使用reducer中的initail状态来禁用btn,当表中的数据完成calusating fire action在reducer中发送新数据到组件状态时