更新动画元素的属性时,react spring useTransition动画出现问题。
我传递给useTransition的对象列表是:
const habits = [
{ id: "V3WV", name: "Go to gym", completions: [] },
{ id: "13t33", name: "Meditate", completions: [] },
{ id: "dghs4", name: "Practice guitar", completions: [] }
];
我的用途Transition是:
const [habitsToShow, setHabitsToShow] = useState(habits);
const transitions = useTransition(habitsToShow, {
from: {
marginTop: -100,
opacity: 0,
transform: "translate3d(-150px,-40px,0)"
},
enter: {
marginTop: 0,
opacity: 1,
transform: "translate3d(0px,0px,0)"
},
leave: {
marginTop: 0,
opacity: 0,
transform: "translate3d(-150px,-40px,0)"
},
update: null
});
我的"输入";以及";离开";动画工作正常,但当我试图将新的完成添加到状态对象的"完成"时;完成";带有:的阵列
const addCompletion = (habit) => {
const indexOfHabit = habitsToShow.map((e) => e.id).indexOf(habit.id);
// This doesn't mutate the state directly but causes re-render / "enter" of habit
setHabitsToShow(
habitsToShow.map((habit, i) =>
i === indexOfHabit
? { ...habit, completions: [...habit.completions, 1] }
: habit
)
);
};
我试图更新的对象被替换;输入";运行的动画不是所需的行为。期望的行为是没有动画发生;完成"-计数器在DOM的元素中得到更新。有人能解决这个问题吗?
下面是一个代码沙盒来说明这种行为:https://codesandbox.io/s/usetransition-react-spring-todo-jcikt
这是动画元素:
{transitions((props, item, state, index) => {
return (
<animated.div
key={item.name}
style={{
...props,
border: "1px solid black",
width: "70%",
marginTop: "5px",
marginBottom: "5px"
}}
className="box"
>
<div key={item.name}>
<h1>{item.name}</h1>
<h3>{`Completed: ${item.completions.length} times`}</h3>
<div>
<button onClick={() => handleRemove(index)}>Remove</button>
<button onClick={() => addCompletion(item)}>Completed?</button>
</div>
</div>
</animated.div>
);
})}
useTransition
使用引用相等来区分其输入数组中的项。如果您通过排列语法创建了一个新对象,那么就它而言,这是一个新项目。
您应该使用keys
属性来指示项目是相同的:
const transitions = useTransition(habitsToShow, {
keys: habit => habit.id,
...
});
更多信息请访问react spring文档。