简体   繁体   English

为什么一个组件的多个实例共享同一状态?

[英]Why do multiple instances of a component share the same state?

I am building a todo list, and one of the functionalities is to display a list of completed tasks when the "completed" text is clicked and hide the list when it is clicked again. 我正在构建一个待办事项列表,其中一项功能是在单击“已完成”文本时显示已完成任务的列表,并在再次单击时隐藏该列表。 However, I can't get the first step - saving the state of the list, whether shown or hidden - to work. 但是,我无法采取第一步-保存列表的状态(无论是显示的还是隐藏的)都无法正常工作。

There are several of these "CompletedRow" components (for different categories of tasks), and while clicking the text does toggle the state successfully, it seems that all these "CompletedRow" components share the same state - they are not independent. 其中有多个“ CompletedRow”组件(用于不同类别的任务),并且单击文本确实可以成功切换状态,但似乎所有这些“ CompletedRow”组件共享相同的状态-它们不是独立的。 Why is this the case when I have already assigned keys to these components, and how can I solve this issue? 当我已经将密钥分配给这些组件时,为什么会出现这种情况?我该如何解决这个问题?

var CompletedRow = React.createClass({    
    getInitialState: function () {
        return {
            show: false
        };
    },
    handleChange: function() {
        this.setState.show = !this.setState.show;
        console.log(this.state.show);
    },
    render: function() {        

        return (<tr>
                <td 
                    className="completed" colSpan="3" onClick={this.handleChange} 
                    > {this.props.count} tasks completed
                </td>
            </tr>);
    }
});

var TaskTable = React.createClass({
    // other code omitted for simplicity
    render: function() {
    var rows = [];
    var completedTasks = 0;

    this.state.taskList.forEach(function(task, index) {

        // do something
         if (completedTasks > 0) {
                rows.push(<CompletedRow 
                    count={completedTasks} 
                    key={getKey()} 
                    taskList={this.state.taskList}                        
                    />);
                completedTasks = 0;
            }

    }.bind(this));

        return (
            <div>            
                <table>
                    <tbody>{rows}</tbody>
                </table>
            </div>
        );
    }
});

This may be a typo, but you have a line in handleChange that is toggling a property attached to the setState function. 这可能是一个错字,但是handleChange中有一行正在切换附加到setState函数的属性。 This is shared by all the components 由所有组件共享

this.setState.show = !this.setState.show;

That line should be 那条线应该是

this.setState({show: !this.state.show});

Also, the console.log on the following line will reflect the old state because setState is asynchronous to allow batching of state changes. 另外,由于setState是异步的,所以允许批处理状态更改,因此下一行的console.log将反映旧状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM