[英]Property 'joiner' does not exist on type '{}'
嘗試設置狀態是 tsx 但當我嘗試從 json 打開數據時返回此錯誤。
Property 'joiner' does not exist on type '{}'. TS2339
這是組件(刪除了無用的代碼)
import Player from '../components/Player'
import listingData from '../libs/listingData'
const Battle = () => {
const [loading, setLoading] = useState(false);
const [creatorState, setCreator] = useState({ health: 100, animate: false, recieve: false });
const [opponentState, setOpponent] = useState({ health: 100, animate: false, recieve: false });
const [data, setData] = useState({});
const loadBattle = () => {
setLoading(true);
const id = parseInt((window.location.pathname).replace("/battle/", ""));
setData(listingData[id])
setLoading(false);
setTimeout(() => triggerAttack("creator"), 5000);
}
useEffect(() => {
loadBattle();
}, [])
return (
<Root>
<Player
weakness={loading ? '' : data.joiner.weakness} //Error triggered here
image=""
status="filled"
price={2352.54}
health={`${creatorState.health}%`}
creator={false}
recieve={creatorState.recieve}
animate={creatorState.animate}
loading={loading}
/>
</Root>
)
}
export default Battle
Player 組件 props 都設置了 any
json 中的對象示例
price: 5251.52,
status: 'filled',
creator: {
weakness: 'wind',
address: '',
image: '',
},
joiner: {
weakness: 'water',
address: '',
image: '',
},
},
我對打字稿很陌生,所以我不熟悉類型,它說我沒有足夠的細節,所以這就是我寫的。
在這種情況下,您必須使用包含預期數據結構的接口鍵入您的狀態。 喜歡:
例子:
interface IUser {
name: string;
}
const [user, setUser] = useState<IUser>({name: 'Jon'});
或者
interface Provider {
connected: boolean;
type: string;
}
const [wearablesList, setWearablesList] = useState<Provider[]>([]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.