到目前为止,在我的代码中,我有一个对象来表示页面上一张图片的所有数据。
this.state = {
img-1: {
x: 0,
y: 0,
rotation: 0
},
img-2: {
x: 20,
y: 200,
rotation: 50
}
}
每次对象接收到一个新的子元素时,它都会向状态添加一个新的
img-id
,每次更新<img id=${id} update={this.update} />
时都会更新该状态。将计算坐标或旋转等功能移动到自定义钩子中,可以大大提高代码的可维护性和测试性,但我并没有看到一种好的方法来使用钩子将所有这些数据存储在集中式对象中。
据我所知,我必须设置一个新的
[img-1, setImg-1] = useState({ x: 0, y:0, rotation: 0 })
对于每个孩子,据我了解,这是不可能的,因为钩子必须在顶层声明或设置一个非常深的对象,这样更新起来会有些笨拙:
[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} }
)}
有更简洁/易读的方法吗?还是我只能把所有内容嵌套在一个对象中?
[img-1, setImg-1] = ...
- Thomas