即使值已更改,对象状态也会返回空值

时间:2020-03-06 08:51:05

标签: javascript reactjs typescript

我有一个名为“表单控制器”的类,用于管理网站上特定表单的状态。

在此类中,我可以加载初始值,这些初始值是从API收集的值,并自动填充到适当的表单字段中。还具有输入更改时的状态更改以及检索状态和初始状态(用于比较更改)的功能。

这是代码:

/**
 * Handles input forms with state management and HTML object data dissection. 
 */
export class FormController {
    initialState = {};
    state = {};

    /**
     * @param intialState Object with decided keys pre-established. Used to assign object key structure. Assigned values irrelevant as will be over-written.
     * @param initialValuesObject Object with pre-defined values. Inserts values into first paramter object if
     * they share keys.
     */
    constructor(initialStateStructure, initialStateValuesObject){
        this.loadInitialValues = this.loadInitialValues.bind(this);
        this.inputChange = this.inputChange.bind(this);
        this.returnState = this.returnState.bind(this);
        this.returnInitialState = this.returnInitialState.bind(this);
        this.resetFormToInitialState = this.resetFormToInitialState.bind(this);

        this.initialState = initialStateStructure;
        this.loadInitialValues(initialStateValuesObject);
    }

    /**
     * Inserts values into common state object keys. 
     * @param initialValuesObject 
     */
    loadInitialValues(initialStateValuesObject){
        try {
            for (let key in initialStateValuesObject){
                if (this.initialState.hasOwnProperty(key)){
                    this.initialState[key] = initialStateValuesObject[key];
                }
            }
            // State and initialState start the same.
            this.state = this.initialState;
        } catch(e) {
            console.log(e);
        }
    }

    inputChange(event){
        event.persist();
        try {
            if (this.state.hasOwnProperty(event.target.name)){
                this.state[event.target.name] = event.target.value;
            } else {
                console.log("Input attribute mismatch. Cannot find attribute: " + event.target.name);
            }
        } catch(e) {
            console.log(e);
        }
    }

    returnState(event?){
        {event && event.preventDefault()}
        return this.state;
    }

    returnInitialState(){
        return this.initialState;
    }

    resetFormToInitialState(){
        this.state = this.initialState;
    }

}

当我尝试返回初始状态或状态时出现问题。当我console.log(this.state / initialstate)时,在浏览器控制台的对象摘要中,我可以看到输入的新值,但是一旦我扩展了日志,所有值都将在其初始位置州。

将对象返回外部始终会将其放在初始状态。我不确定是什么问题。

0 个答案:

没有答案