【问题标题】:react native TypeError: this.setState is not a function.'this.setState' is undefined)react native TypeError: this.setState is not a function.'this.setState' is undefined)
【发布时间】:2020-05-23 18:29:52
【问题描述】:

我正在从开源 api 获取 json。我想将它存储为一个状态。无法以状态存储 json 数据。我需要使用这个 json 数据来匹配一个城市与 json 中的一个城市。我需要将它存储在状态中。会非常有用。请帮忙!

构造函数部分

constructor(props) {
  super(props)
  this.state = {
    location: null,
    loading: false,
    userLatitude: null,
    userLongitude: null,
    userCity: null,

    covidZones: []

  }

  this._requestLocation = this._requestLocation.bind(this)
  this.getZone = this.getZone.bind(this)

}

功能部分

getZone() {
  axios.get('https://api.covid19india.org/zones.json')
    .then(function(response) {

      this.setState({
        covidZones: response.data.zones
      })

    })
    .catch(function(error) {
      // handle error
      console.log(error);
    })
    .finally(function() {
      // always executed
    })
}

渲染部分

render() {
    const { location, loading } = this.state;

    return (
            <View>
                <Button
                    disabled={loading}
                    title="Get Location"
                    onPress={this._requestLocation}
                />

                <Text>{this.state.userCity}</Text>

                {this.getZone()} // calling the function, right here


                {loading ? (
                    <ActivityIndicator />
                ) : null}
                {location ? (
                    <Text>
                        {JSON.stringify(location, 0, 2)}
                    </Text>
                ) : null}
            </View>
        )
}

【问题讨论】:

  • 你应该在componentDidMount()生命周期钩子中运行你的数据获取操作。参考这里:reactjs.org/docs/…

标签: javascript android node.js reactjs react-native


【解决方案1】:

您在 render 函数中调用了一个 API {this.getZone()}。恐怕这会导致无限循环,因为在每次调用之后,setState 将被触发,而这又会调用render 函数。

要解决这个问题: 1. 从render 方法中删除{this.getZone()}。 2. 把这个放到componentDidMount

componentDidMount(){
this.getZone()
}

【讨论】:

    【解决方案2】:

    我为您准备了一个使用reactjs 的示例。 react-native 应遵循相同的技术。请遵循以下示例:

    import React from "react";
    import axios from 'axios';
    
    export default class ZoneListPage extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                location: null,
                loading: false,
                userLatitude: null,
                userLongitude: null,
                userCity: null,
                covidZones: []
            };
        }
        componentDidMount() {
            this.setState({
                loading: true,
                covidZones: null
            });
            fetch("https://api.covid19india.org/zones.json")
                .then(res => res.json())
                .then(
                    (result) => {
                        console.log(result.zones, 'zones');
                        this.setState({
                            loading: false,
                            covidZones: result.zones
                        });
                    },
                    (error) => {
                        this.setState({
                            isLoaded: true,
                            error
                        });
                    }
                )
        }
    
        render() {
            return (
                <React.Fragment>
                    <ul>
                        {
                            this.state.covidZones ? this.state.covidZones.map((zone, index) =>
                                    <div key={index}>
                                        <div key={index}> District: <span key={index}>{zone.district}</span></div>
                                        <div key={index}> District Code: <span key={index}>{zone.districtcode}</span></div>
                                        <div key={index}> Last Updated: <span key={index}>{zone.lastupdated}</span></div>
                                        <div key={index}> Source: <a key={index} href={zone.source}>source</a></div>
                                        <div key={index}> State: <span key={index}>{zone.state}</span></div>
                                        <div key={index}> State Code: <span key={index}>{zone.statecode}</span></div>
                                        <div key={index}> Zone: <span key={index}>{zone.zone}</span></div>
                                        <hr/>
                                    </div>)
                                :
                                null
                        }
                    </ul>
                </React.Fragment>
            );
        }
    }
    

    这是输出的图像

    【讨论】:

      【解决方案3】:

      你不应该在你的render() 方法中调用getZone() 函数,因为setState() 方法会弄脏你的状态并且应用程序可能会进入无限渲染循环并且d react 会抛出错误。因此,您必须在任何生命周期方法中调用它。

      【讨论】:

        【解决方案4】:

        您看到setState is not a function 错误的原因是,在您的提取的.then 函数中this 将不再引用该组件。你必须用箭头函数绑定this,你可以像这样修复setState错误:

         axios.get('https://api.covid19india.org/zones.json')
                    .then((response) => {
                        this.setState({ covidZones: response.data.zones })
                    })
                    .catch((error) => {
                        // handle error
                        console.log(error);
                    })
                    .finally(()=> {
                        // always executed
                    })
        

        【讨论】:

          【解决方案5】:

          有 3 种不同的解决方案适合您。

          getZone() {

              axios.get('https://api.covid19india.org/zones.json')
                  .then((response)=> {
          
                      this.setState({ covidZones: response.data.zones })
          
                  })
                  .catch((error) =>{
                      // handle error
                      console.log(error);
                  })
                  .finally(()=> {
                      // always executed
                  })
          }
          

          var self = this;
          
          axios.get('https://api.covid19india.org/zones.json')
                  .then(function (response) {
          
                      self.setState({ covidZones: response.data.zones })
          
                  })
                  .catch(function (error) {
                      // handle error
                      console.log(error);
                  })
                  .finally(function () {
                      // always executed
                  })
          

          axios.get('https://api.covid19india.org/zones.json')
                      .then(function (response) {
          
                          this.setState({ covidZones: response.data.zones })
          
                      })
                      .catch(function (error) {
                          // handle error
                          console.log(error);
                      })
                      .finally(function () {
                          // always executed
                      }).bind(this));
          

          【讨论】:

            猜你喜欢
            • 2020-01-06
            • 2017-02-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-09-26
            • 1970-01-01
            • 2015-06-24
            • 2021-06-21
            相关资源
            最近更新 更多