无法从componentDidMount中调用setState

时间:2017-03-06 04:03:44

标签: reactjs

我总是得到消息:

  

警告:setState(...):只能更新已安装或已安装   零件。这通常意味着您在已卸载时调用了setState()   零件。这是一个无操作。请检查管理员的代码   成分

当我在setState函数外使用componentDidMount时。

这是我的源代码:

class Admin extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            mainModal: false,
            itemId: null,
            bulkRemove: true,
            params: {},
            defaultRole: null,
            dataLoaded: store.getState().adminReducer.list.length?true:false
        };
        this.list = this.list.bind(this);
        this.toggleModal = this.toggleModal.bind(this);
        this.handleFilter = this.handleFilter.bind(this);
        this.handleCheck = this.handleCheck.bind(this);
        this.handleCheckAll = this.handleCheckAll.bind(this);
        this.handleRemove = this.handleRemove.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handlePageChange = this.handlePageChange.bind(this);

        this.filterTimeout = null;
    }

    componentDidMount(){
        ...
        this.list();
        // this.setState({dataLoaded: true}); // OK when call here
        ...
    }

    list(outerParams={}, page=1){
        let params = {
           page
        };

        if(!isEmpty(outerParams)){
            params = {...params, ...outerParams};
        }

        Tools.apiCall(apiUrls.list, params, false).then((result) => {
            if(result.success){
                console.log(this);
                // output of above console.log -> Admin {props: Object, context: undefined, refs: Object, updater: Object, state: Object…}
                // this.setState({dataLoaded: true}); // Error when call here or inside setInitData function
                this.setInitData(result);
            }
        });
    }
}

当我使用babel预设es2015时,一切正常,但与es2016es2017相同。

0 个答案:

没有答案