如果数组处于全局状态,如何通过索引 reassign/replace 数组的值
How to reassign/replace a value of an array by index if its in a global state
我有一个全局状态,它是一个数组 [1,0, null,1,0....] 我想按索引访问数组比方说索引 5 我只想用 1 替换该值我有数组和索引,但我不知道如何重新分配和更新状态
const setarrayFlags = useSetRecoilState(arryofFlags); //setting my global array
const setPosition = useSetRecoilState(Position); // I keep track of the position
setarrayFlags([1,0,null,1,0...); // set array with values
// This is called from a child componet
const arryofFlag = useRecoilValue(arryofFlags); // get my global array
let FlagPosition = useRecoilValue(Position); // get current position
arryofFlag[FlagPosition] = 1; // this is how I reassign the value on the current position but not sure how to use setarrayFlags again to set it global again without replacing the whole array just that position
setarrayFlags(arryofFlag[FlagPosition] = 1); //cant be this way
因此,您可以这样写 arryofFlag[CardPosition] = 1;
而不是这一行:
const tempArray = [...arryofFlags];
tempArray[CardPosition] = 1
setarrayFlags(tempArray)
我有一个全局状态,它是一个数组 [1,0, null,1,0....] 我想按索引访问数组比方说索引 5 我只想用 1 替换该值我有数组和索引,但我不知道如何重新分配和更新状态
const setarrayFlags = useSetRecoilState(arryofFlags); //setting my global array
const setPosition = useSetRecoilState(Position); // I keep track of the position
setarrayFlags([1,0,null,1,0...); // set array with values
// This is called from a child componet
const arryofFlag = useRecoilValue(arryofFlags); // get my global array
let FlagPosition = useRecoilValue(Position); // get current position
arryofFlag[FlagPosition] = 1; // this is how I reassign the value on the current position but not sure how to use setarrayFlags again to set it global again without replacing the whole array just that position
setarrayFlags(arryofFlag[FlagPosition] = 1); //cant be this way
因此,您可以这样写 arryofFlag[CardPosition] = 1;
而不是这一行:
const tempArray = [...arryofFlags];
tempArray[CardPosition] = 1
setarrayFlags(tempArray)