繁体   English   中英

为什么反应不运行。map function?

[英]why react does not run .map function?

import React, {Component} from 'react';
import {View, Text} from 'react-native';
import axios from 'axios'


//servislere bağlanabilmek için class haline getireceğiz
class Liste extends Component {
    state = {data: [] };
    UNSAFE_componentWillMount() {
        console.log('componentWillMount');
        axios.get('https://reqres.in/api/users')
        .then(response => this.setState({ data: response.data}));
    }
    componentDidMount() {
        console.log('componentDidMount');
    }

    renderData() {
        return this.state.data.map( responseData => 
            <Text> {responseData.title} </Text>    
    );
    }

    render() {
        console.log('gelen data', this.state);
        console.log('render');
        return (
            <View style={{marginTop: 5}}>
                {this.renderData()}
            </View>
        );
    }
}

export default Liste;

这是我的 Liste.js 组件脚本。 我有一个错误告诉我“this.state.data.map 不是函数” 我应该怎么办? 我是怎么了?

编辑:

正如@Bergi 正确指出的那样,我们真的不需要bind renderData function,因为该方法可以正确使用state 我冒昧地创建了一个小提琴来检查问题,它确实是 API 调用的response

response.data返回一个objectresponse.data.data是一个Array 它在小提琴中得到纠正

UNSAFE_componentWillMount() {
   console.log('componentWillMount');
   axios.get('https://reqres.in/api/users')
    .then(response => {  
         this.setState({ data: response.data.data})
     });
}


您需要将renderData bind到正确的词法 scope 以使反应能够引用其中定义的组件的 state。 另外,我建议在设置 state 之前检查从 API 调用返回的response.data

其他选项是使用箭头 function renderData = () => {...}但它有一个缺点,即您的组件的每个实例都会获得自己的 function 副本,从而增加其 ZCD69B4957F08CD818D7BBF3D61 占用空间。

您可以执行以下操作:

import React, {Component} from 'react';
import {View, Text} from 'react-native';
import axios from 'axios'


//servislere bağlanabilmek için class haline getireceğiz
class Liste extends Component {
    constructor(props) {
      super(props);
      this.state = {data: [] };
      this.renderData = this.renderData.bind(this);
    }
    
    UNSAFE_componentWillMount() {
        console.log('componentWillMount');
        axios.get('https://reqres.in/api/users')
        .then(response => { 
            if(response && Array.isArray(response.data)) {
               this.setState({ data: response.data})
            } else {
              // handle the type mismatch here
            }
         });
    }
    componentDidMount() {
        console.log('componentDidMount');
    }

    renderData() {
        return this.state.data.map( responseData => 
            <Text> {responseData.title} </Text>    
        );
    }

    render() {
        console.log('gelen data', this.state);
        console.log('render');
        return (
            <View style={{marginTop: 5}}>
                {this.renderData()}
            </View>
        );
    }
}

export default Liste;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM