如何使用反应钩子动态创建 objects 状态?

How to dynamically create objects in state with react hooks?

到目前为止,在我的代码中,我有一个 object 代表页面上图像的所有数据

this.state = {
    img-1: {
        x: 0,
        y: 0,
        rotation: 0
    },
    img-2: {
        x: 20,
        y: 200,
        rotation: 50
    }
}

每次 object 收到一个新的 child 时,它都会添加一个新的 img-id 到每次 <img id=${id} update={this.update} /> 更新时更新的状态。

将计算坐标或旋转等功能移动到他们自己的自定义挂钩中将在可维护性和测试方面极大地改进我的代码,但我真的没有看到将所有这些数据集中存储的好方法 object 带钩子。

据我所知,我必须设置一个新的

[img-1, setImg-1] = useState({ x: 0, y:0, rotation: 0 })

for every child,据我所知,这是不可能的,因为必须在顶层声明钩子或设置一个非常深的 object,这会有点笨拙更新:

[images, setImages] = useState({
    img-1: {
        x: 0,
        y: 0,
        rotation: 0
    }
})

const createImg = (newImg) => { setImages({...images, newImg}) }

const updateImg = (id, updatedImg) => {
    setImages({ ...images, [`img-${id}`]{...updatedImg} }
)}

是否有更简洁/更具可读性的方法,或者我只需要求助于将所有内容嵌套在一个 object 中?

您可以使用 useReducer 而不是使用 useState 并更好地控制您的状态并处理状态的动态添加

const initialState = {
    img-1: {
        x: 0,
        y: 0,
        rotation: 0
    }
}

const reducer= (state, action) =>{
   switch(action.type) {
        'ADD_IMAGE': return  {
             ...state,
             [action.itemkey]: action.payload
         }
         'UPDATE_IMAGE: return {
             ...state,
             [action.id]: {...state[action.id], ...action.payload}
         }
         default: {
            return state;
         }
   }
}

在功能组件中

const [state, dispatch] = useReducer(reducer, initialState);


const createImg = (newImg) => { dispatch({ type: 'ADD_IMAGE', payload: {newImg}, itemKey: `item-${Object.keys(state).length + 1}`

const updateImg = (id, updatedImg) => {
   dispatch({type: 'UPDATE_IMAGE', id, payload: updatedImg })
)}