将对象推送到状态对象中的数组。 ReactJS

时间:2017-01-20 18:16:34

标签: javascript arrays reactjs closures

我将从代码开始:

class App extends React.Component{
    constructor() {
        super();
        this.state = {
            todo: []
        };
    }

    addTask(newTask) {
        let todo = this.state.todo.slice();
        newTask.id = this.nextId();
        todo.push(newTask);
        this.setState({todo}); //React method to update state object
    }

    //fake id
    nextId() {
        let id = 0;
        this.nextId = () => {
            return ++id;
        };

        return id;
    }

    render() {
        return (
            <div>
                <ToDoList list={this.state.todo} />
                <ModalDialog onFormSubmission={this.addTask.bind(this)}/>
                <ActionButton />
            </div>
            );
    }

}
;

现在我希望每次调用addTask(newTask) - this.state.todo数组后,将使用另一个具有唯一id的元素填充。例如:

addTask({title: "aa", description: "bb"});
addTask({title: "aa", description: "bb"});

应该给我:

this.state.todo[0].id === 0
this.state.todo[1].id === 1

但是当我像上面那样把两个具有相同的值的对象时,这是真的:

this.state.todo[0].id === 1
this.state.todo[1].id === 1

我不明白为什么。当我使用唯一值推送对象时,它确实有效。

1 个答案:

答案 0 :(得分:1)

我发现了问题:

class ToDoForm extends React.Component {
    constructor() {
        super();
        this.state = {
            title: '',
            description: ''
        };
    }

    handleSubmit(event) {
        this.props.onFormSubmission(this.state); //on form submission is `addTask` in this context
        event.preventDefault();
    }    

    handleChange() {
        this.setState({
            title: this.refs.title.value,
            description: this.refs.description.value
        });
    }

}

更正:

handleSubmit(event) {
    event.preventDefault();
    let {title, description} = this.state;
    this.props.onFormSubmission({title, description});
}   

我正在传递可变对象。我觉得愚蠢:)。