我怎麼能流檢查該文件正確, 該組件上的狀態的條件呈現基地, 流說Property cannot be accessed on possibly null value
狀態對象的流條件值?
什麼,如果我有一個更復雜的狀態結構如{} user.owner.name。 .. 如何正確設置類型?
type User = {
title: string,
description: string,
year: string,
imdbID: string,
poster: string,
trailer: string
};
class AllUser extends React.Component {
state: {
repos: Array<?User>,
repos2: Array<?User>
};
handleChange:() => void;
filterItem:() => void;
constructor() {
super();
this.state = {
repos: [],
repos2: []
};
this.handleChange = this.handleChange.bind(this);
this.filterItem = this.filterItem.bind(this);
}
componentDidMount() {
if (this.state.repos.length === 0) {
fetchPopularRepos("all").then((repos: Array<?User>) => {
this.setState({
repos: repos,
repos2: repos
});
});
}
}
render() {
if (this.state.repos.length === 0) {
return (
<div>loading</div>
);
}
return (
<div>
{this.state.repos.map(repo => <p>{repo.name}</p>)}
</div>
)
}
}
爲什麼使用'Array '而不是'Array'? '?'表示數組可能有空/未定義的值,但是他們在每個條目上都執行'repo.name'。根據您提供的類型,這是一個有效的錯誤。 –
loganfsmyth
你的意思是'回購:?數組',並通過這個流程將聰明地選擇'repo.name'或不? –
Liuuil
根本不需要問號。數組允許爲空。你現在擁有的是「一個null或者一個用戶的數組」,所以你說數組中的項可以是null,但是代碼本身並沒有暗示你最終會用null來代替一個'用戶'對象。 – loganfsmyth