i创建一个从服务器获取数据的组件,然后在屏幕上显示数据。当我直接使用反应的视图时,屏幕看起来不错。
之后,我通过将代码段移动到新组件(TwoGroupItemsView
(来重构代码以使其重复使用:
export class MainComponent extends Component {
componentDidMount() {
return fetch('https://mycompany.com/items')
.then(res => res.json())
.then(json => {
this.setState({
isLoading: false,
items: json.data,
}, function(){
});
}
}
render() {
return (
<View>
<View>
{
this.state.items != null &&
<TwoGroupItemsView title={'Group 1'} items={this.state.items}/>
}
</View>
</View>
);
}
}
class TwoGroupItemsView extends View {
constructor(props) {
super(props);
}
render() {
return (
<View style={{marginTop: 16}}>
//... FlatList for items array
</View>
)
}
}
我总是得到:
typeError:null不是对象
评估" this.state.items
"。
您可以告诉我创建自己可重复使用的视图的方法吗?
您的状态被异步设置。在承诺解决之前,请尝试将其明确初始化。下面的一些可能性。
声明初始状态:
export class MainComponent extends Component {
state = {
isLoading: true, // sample values
items: null
}
或在构造函数中设置:
export class MainComponent extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true, // sample values
items: null
};
}
或加强警卫:
render() {
return (
<View>
<View>
{
this.state && this.state.items != null &&
<TwoGroupItemsView title={'Group 1'} items={this.state && this.state.items}/>
}
</View>
</View>
);
}
re写下您的渲染函数。
render() {
return (
<View>
<View>
{
this.state.items ?
<TwoGroupItemsView title={'Group 1'} items={this.state.items}/> : null
}
</View>
</View>
);
}