"use client";
import React, {memo, useEffect, useState} from 'react'
import {animated, useTransition} from "@react-spring/web";
const Test = () => {
useEffect(() => {
changeItem()
}, [])
const [items, setItems] = useState<string[]>(["1", "2", "3", "4"]);
const addItem = () => {
const newItem = `Item ${items.length + 1}`;
setItems([...items, newItem]);
};
const removeItem = () => {
if (items.length === 0) return;
const newItems = items.slice(0, -1);
setItems(newItems);
};
const changeItem = () => {
setItems(["1", "2", "3", "4"])
}
const [transitions, api] = useTransition(items, () => ({
from: {opacity: 0},
enter: {opacity: 1},
leave: {opacity: 1},
config: {duration: 1000}
}))
const transitionsTest = useTransition(items, {
from: {opacity: 0},
enter: {opacity: 1},
leave: {opacity: 1},
config: {duration: 1000}
});
return (
<div>
<div>
<button onClick={addItem}>Add Item</button>
<button onClick={removeItem}>Remove Item</button>
<button onClick={changeItem}>Change Item</button>
</div>
<div>
{transitions((style, item) => (
<animated.div style={style}>{item}</animated.div>
))}
</div>
<hr/>
<div>
{transitionsTest((style, item) => (
<animated.div style={style}>{item}</animated.div>
))}
</div>
</div>
);
}
export default memo(Test)
I just started learning and referred to the example in the document, that is transitions
, but it doesn’t work. animated.div
will never be displayed because it is always style="opacity: 0;"
Then I checked some articles on the Internet and found another way to write it, which is transitionsTest
, and found that it can be used normally.
I’m confused as to why the two writing methods lead to different results. I checked the typescript types of the two and found no difference.
package.json
file
"dependencies": {
"@next/mdx": "^13.4.4",
"@react-spring/web": "^9.7.3",
"@reduxjs/toolkit": "^1.9.7",
"@types/node": "18.15.11",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.0",
"eslint": "8.38.0",
"eslint-config-next": "^14.2.3",
"immer": "^10.0.4",
"next": "^14.2.3",
"normalize.css": "^8.0.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-redux": "^8.1.3",
"redux": "^4.2.1",
"typescript": "^5.4.5",
"use-immer": "^0.9.0"
},
"devDependencies": {
"sass": "^1.61.0"
}
Can anyone explain why?