8

While I am writing test case for my react component I am getting

TypeError: Cannot assign to read only property 'x' of object '#'

wherein while the application run it does not throw similiar error

The code for it is pretty basic

this.props.defaultForm = true;

Why the behavior is different for test and actual application RUN?

What would be work around if I want to write a test case?


how do I toast the number of checked boxes in my RecyclerView?

My code below works perfect when the activity loads with all checkboxes checked, or all checkboxes unchecked, and they are checked or unchecked from that point on, but the problem is that in reality the activity might load with SOME checkboxes checked.

I suppose the key is count = 0; If I could set count to the number of checked boxes when the form loads...

This is what I have in the setOnClickListener(new View.OnClickListener() { of my adapter, works for when all checkboxes start from a checked or unchecked position:

                //we want to keep track of checked boxes
                int count;
                count = 0;
                int size = MatchingContactsAsArrayList.size();
                for (int i = 0; i < size; i++) {
                    if (theContactsList.get(i).isSelected) {
                        count++;
                    }

                }

                  if (count == 0) {

                        Toast.makeText(context_type, "count is 0!", Toast.LENGTH_SHORT).show();

                } else {

                        Toast.makeText(context_type, "The count is " + count, Toast.LENGTH_SHORT).show();

                }
4

2 回答 2

24

有办法做到这一点;

使用Object.assign()方法或 JavaScript扩展运算符创建对象的“克隆

let clone = Object.assign({}, this.props);

或者

let clone = { ...this.props };

然后,更改您需要的值并返回克隆作为结果。

let clone = Object.assign({}, this.props);
clone.defaultForm = true;
return clone;

但请考虑 Object.assign() 创建对象的浅表副本。因此,如果您需要深拷贝,我建议使用以下方法:

let deepClone = JSON.parse(JSON.stringify(this.props));
deepClone.defaultForm = true;
return deepClone;

在这里,“字符串化”对象然后将其解析回来将创建对象的全新深度克隆副本。

于 2018-07-17T11:32:20.760 回答
-2

您不能更改组件的属性。它是只读的。

如果你想改变它。您必须使用connectfromredux和函数mapStateToProps

您可以在此处找到更多信息:https ://redux.js.org/basics/usage-with-react#implementing-container-components

于 2018-02-20T12:31:45.830 回答