【问题标题】:undefined is not an objectundefined 不是对象
【发布时间】:2017-12-02 08:50:59
【问题描述】:
TypeError: undefined is not an object (evaluating 'this.props.data.map')
  

appBodyData

render(){
  
    let articles =this.props.data.map(function(articleData,index) {
      return (
        <Card>
        <CardItem>
          <Body>
            <Text>
            {articleData.address.city}
            </Text>
          </Body>
        </CardItem>
      </Card>
     
      )
    });
    return (
        <Content>
          {articles}
         </Content>
     );
  }
  
**[appBody:][1]**

getData(){
    return fetch("https://jsonplaceholder.typicode.com/users")
    .then((response) => response.json())
    .then((responseJson) => {
    this.setState({data:responseJson.array});
    })
    .catch((error) => {
      console.error(error);
    });
    
    
  }
  componentDidMount(){
    this.getData();
  }
  render() {
    return (
        <AppBodyData data={this.state.data}/>
     );

}

当我尝试在模拟器中运行时显示此错误。 我该如何解决这个错误。 似乎地图功能无法获取数据。 反应本机cli版本:50 SDK版本:23

【问题讨论】:

    标签: json react-native


    【解决方案1】:

    因为您的 fetch 是异步的,所以在第一次渲染时 this.props.data 是未定义的。

    此外,您需要使用this.state.data,因为获取的结果是设置状态而不是道具

    首先在构造函数中设置初始状态:

    constructor(props) {
        super(props);
        this.state = {
          data: []
        }
      }
    

    然后改变状态

    let articles =this.state.data.map(function(articleData,index) {
    

    【讨论】:

      【解决方案2】:

      由于 fetch 方法,您获得了 null 值,它需要时间来获取数据,因此在 if 条件下呈现

      render(){
          return (
            <Content>
              {this.props.data?this.props.data.map((articleData,index)=>{
                return <Card>
                  <CardItem>
                    <Body>
                      <Text>
                      {articleData.address.city}
                      </Text>
                    </Body>
                  </CardItem>
                </Card>          
                }):null}     
             </Content>
           );
        }
      

      【讨论】:

        猜你喜欢
        • 2017-01-05
        • 2019-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-14
        • 2015-07-16
        • 2020-07-16
        • 2018-08-28
        相关资源
        最近更新 更多