I have an array of roundedBox gemoetry (myShape)
and I want to know if I can change the position of one of the shapes inside the array,
I can replace it the shape at the index I want with a new one with the position I want,
but this isn't good,
I don't want to create a new one, I only want to update the position of the already existing one, and update it on the canvas.
here's what I have:
This is what I wanna do: shapes[1].props.position = [150, 0, 150]
const [shapes, setShapes] = useState([<MyShape key={0} position={[0, 0, 0]} />, <MyShape key={1} position={[100, 0, 100]} />, <MyShape key={2} position={[200, 0, 200]} />])
useEffect(() => {
function handleKeyUp(event) {
if (event.key === 'r') {
shapes[1] = <MyShape key={1} position={[150, 0, 150]} />
// shapes[1].props.position = [150, 0, 150];
setShapes([...shapes]);
console.log(shapes)
}
}
window.addEventListener('keyup', handleKeyUp)
return () => {
window.removeEventListener('keyup', handleKeyUp)
}
}, [shapes])
return (
<group >
{[...shapes]}
</group>
)
CodePudding user response:
shapes[1] = <MyShape key={1} position={[150, 0, 150]} />
This line in your code directly modify the state which is a bad idea. You can read more about it here.
I would suggest that instead of storing elements in your state. Just store the position in your state instead.
I have not tested this but it will probably look something like this:
const [positions, setPositions] = useState([
[0, 0, 0],
[100, 0, 100],
[200, 0, 200],
]);
useEffect(() => {
function handleKeyUp(event) {
if (event.key === 'r') {
setPositions((prevPositions) => {
const newPositions = [...prevPositions];
// You might want to check for null index here.
newPositions[1] = [150, 0, 150];
return newPositions;
});
}
}
window.addEventListener('keyup', handleKeyUp);
return () => {
window.removeEventListener('keyup', handleKeyUp);
};
}, [shapes]);
return (
<group>
{positions.map((position, idx) => (
// Using idx here for simplicity purposes.
<MyShape key={idx} position={position} />
))}
</group>
);