gpt4 book ai didi

javascript - 将对象传递给可重用 View 会出现错误 : null is not object (evaluating . ..)

转载 作者:行者123 更新时间:2023-11-30 20:39:25 25 4
gpt4 key购买 nike

我创建了一个从服务器获取数据然后在屏幕上显示数据的组件。直接使用 react-native views 时画面看起来不错。

之后,我通过将代码片段移动到新组件 (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 is not an object

在评估“this.state.items”时。

你能告诉我如何创建我自己的可重用 View 吗?

最佳答案

您的状态正在异步设置。尝试在 Promise 解析之前显式初始化它。以下是一些可能性。

声明初始状态:

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>
);
}

关于javascript - 将对象传递给可重用 View 会出现错误 : null is not object (evaluating . ..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49461201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com