gpt4 book ai didi

javascript - 为什么我收到错误 : TypeError: Cannot read property 'map' of undefined?

转载 作者:行者123 更新时间:2023-12-02 22:24:01 25 4
gpt4 key购买 nike

收到错误:TypeError:无法读取未定义的属性“map”。在重新加载页面之前,它工作正常。但是当我重新加载页面时出现错误。我想从数组中获取对象值。

enter image description here

import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {fetchData} from '../../actions/fetchData';

class Menu extends Component {
componentDidMount() {
this.props.fetchData();
}

render() {
const {data, isFetching} = this.props.data;

if (isFetching) {
return (
<View>
<ActivityIndicator size={'large'} />
</View>
);
} else {
return (
<View
style={{
flex: 1,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>
{data.categories.map(nm => nm.name)}
{/* {console.log("data",data.categories.map(nm => nm.name))} */}
</Text>
</View>
);
}
}
}

function mapStateToProps(state) {
return {
data: state.data,
};
}

function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({fetchData}, dispatch),
};
}

export default connect(mapStateToProps, mapDispatchToProps)(Menu);

最佳答案

我不是react-native开发人员,但在 react 上有一些工作经验。我能理解的如下:

this.state = {
data: this.props.data,
};

在上面的代码中 constructor ,首先用 state.data 进行初始化,当调用类实例时,它将是 undefined 。因为当调用头等舱时,this.props.dataundefined .

componentDidMount() {
this.props.fetchData();
}

constructor之后的任务完成,上面的代码将被执行,其数据显示在console.log中。但返回的数据永远不会分配给任何变量。这意味着,获取数据后,this.state.data仍然是undefined .

那么什么时候执行<Text>{this.state.data.data.categories.map(nm => nm.name)}</Text> , this.state.data将是未定义的。为了解决这个问题,您可以尝试以下代码:

class Menu extends Component {

componentDidMount() {
this.props.fetchData();
}

render() {
return (
<View>
<Text>{this.props.data.data.categories.map(nm => nm.name)}</Text>
</View>
);
}
}

最后一件事,我强烈建议您学习 React 开发生命周期。谢谢

关于javascript - 为什么我收到错误 : TypeError: Cannot read property 'map' of undefined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59125773/

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