嗨,我是React的初学者。我正在开发我的任务,我需要声明一个带有空值的数组:
this.state = {
position: [null,null,null,null,null,null,null,null]
};
之后,我为此数组分配了一些值,但是我的应用程序确实要求每个池只能更改一次。问候
如果将任务更改为 position
,只能从 null
更改为另一个值,而不是再次更改为 null
,那么它变得容易
setPool(i, pool) {
if(pool === null) return; // prevent that any position gets set back to `null`
this.setState(({ position }) => {
if(position[i] !== null) return; // prevent that a pool gets set twice
return { position: position.map((v, i2) => i === i2 ? pool : v) };
});
}
您可以将Proxy
用于此
let arr = Array(5).fill(null);
const validator = {
set:function(obj,prop,value){
if(obj[prop] !== null) throw "You can't change it again"
else obj[prop] = value;
}
}
var p = new Proxy(arr, validator);
p[1] = 2; //the element is successfully changed
console.log(JSON.stringify(p))
p[1] = 3; // changing again throw error.