简体   繁体   中英

Property 'joiner' does not exist on type '{}'

Trying to set state is tsx but I get this error returned when I try open data from json.

Property 'joiner' does not exist on type '{}'. TS2339

Here is the component (removed useless code)


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

The Player component props are all set the any

example of object in json

        price: 5251.52,
        status: 'filled',
        creator: {
            weakness: 'wind',
            address: '',
            image: '',
        },
        joiner: {
            weakness: 'water',
            address: '',
            image: '',
        },
    },

Im pretty new to typescript so I am not familiar with types, its saying i dont have enough details so this is what im writing.

In that case you have to type your state with an interface containing the expected data structure. Like:

Example:

interface IUser {
  name: string;
}
const [user, setUser] = useState<IUser>({name: 'Jon'});

or

interface Provider {
  connected: boolean;
  type: string;
}
const [wearablesList, setWearablesList] = useState<Provider[]>([]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM