[英]React typescript Property 'map' does not exist on type 'User'
我正在嘗試對 typescript 做出反應。 我已經用 object 初始化了 useState 但不能使用 map function 和 ZA8CFDE6331BD59EB2ACZ66F14Z
這是我得到的錯誤
“用戶”類型上不存在屬性“地圖”
這是代碼。
先感謝您
interface User {
name : string,
email : string,
stream_key : string,
}
const App = () => {
const [liveStreams, setLiveStreams] = useState<User>({
name : '',
email : '',
stream_key : ''
})
// setting livestreams
const getStreamsInfo = (live_streams) => {
axios.get('http://192.168.43.147:4000/streams/info', {
}).then(res => {
console.log(res.data)
setLiveStreams({
name: res.data.name,
email: res.data.email,
stream_key: res.data.stream_key
})
});
}
return (
{liveStreams.map(data => <Text>{data.email}</Text>)}
)
您只有一個User
object,而不是它們的數組。 任何一個:
只需使用 object (最好使用單數而不是復數作為 state 變量的名稱),或
改為使用對象數組。
例如,對於 #1,如果您使用名稱liveStream
,它將如下所示:
return <Text>{liveStream.email}</Text>;
鑒於你說過
實際上 res.data 包含多個用戶的數據。 如何使用 typescript 使用對象數組? 對不起新手問題
在評論中,看起來你想要#2,這意味着:
使您的初始數據成為一個空數組。
const [liveStreams, setLiveStreams] = useState<User[]>([]); // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^−−^^
當您收到列表時,請使用整個列表:
const getStreamsInfo = (live_streams) => { axios.get('http://192.168.43.147:4000/streams/info', { }).then(res => { // To *replace* state with the list in `res.data`: setLiveStreams(res.data); // >>OR<< to **add to** the current state, appending the list from `res.data`: setLiveStreams(streams => [...streams, ...res.data]); }); }
為您的Text
元素添加key
屬性,因為它們是數組中的條目。
在您的情況下,實際的解決方案是在嘗試使用 map 方法之前使用類型保護來檢查您是否有一個數組。
if (liveStreams instanceof Array) {
liveStreams.map(data => <Text>{data.email}</Text>);
}
interface User {
name : string,
email : string,
stream_key : string,
}
const App = () => {
const [liveStreams, setLiveStreams] = useState<User[]>([{
name : '',
email : '',
stream_key : ''
}])
// setting livestreams
const getStreamsInfo = (live_streams) => {
axios.get('http://192.168.43.147:4000/streams/info', {
}).then(res => {
console.log(res.data)
// is the `res.data` an Array Object?
// or u may just do like that
/*
* const { data } = res
* // if `data` type is user[]
* setLiveStreams(data)
*/
setLiveStreams([{
name: res.data.name,
email: res.data.email,
stream_key: res.data.stream_key
}])
});
}
return (
{liveStreams.map(data => <Text>{data.email}</Text>)}
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.