【问题标题】:accessing object attributes in the react render method在反应渲染方法中访问对象属性
【发布时间】:2017-01-19 01:08:55
【问题描述】:

我编写了一个小的反应组件,它从开放的天气 api 中获取一些数据。获取成功,我可以在响应中获取一个 json 对象。

然后我使用 this.setState({}) 将此响应保存到组件状态

并且反应开发工具显示预测对象实际上保存在状态中。

但是,当我开始渲染任何数据时,我总是会收到一条错误消息,指出“无法读取 null 的属性“预测”。

下面是反应组件和对象本身的屏幕截图。

    export default class Weather extends Component {
    getWeather () {
        var self = this;

        fetch('http://api.openweathermap.org/data/2.5/weather?zip=sl44jn,uk&units=metric&APPID=ed066f80b6580c11d8d0b2fb71691a2c')  
            .then (function (response) {  
                if (response.status !== 200) {  
                    console.log('Looks like there was a problem. Status Code: ' + response.status);  
                    return;  
                }

                response.json().then(function(data) {  
                    self.setWeather(data);
                });
            })

            .catch (function (err) {  
                console.log('Fetch Error :-S', err);  
            });
    }

    setWeather (forecast) {
        console.log(forecast);
        this.setState({
          forecast: forecast.name
        })
    }

    componentWillMount () {
        this.getWeather();
    }

    componentDidMount () {
        // window.setInterval(function () {
    //          this.getWeather();
    //  }.bind(this), 1000);
    }

  render() {
    return (
        <h1>{this.state.forecast}</h1>
    )
  }
}

这是数据对象本身,现在我只是尝试访问 name 属性。

【问题讨论】:

    标签: json object reactjs fetch


    【解决方案1】:

    看起来您忘记了几件事,为了将Component 绑定到setState,您需要最好在构造函数中将其绑定到this。您还需要设置初始状态,在您的情况下是一个空对象,您可以将整个响应保存在对象中并仅访问您想要的部分。看看:

    export default class Weather extends Component {
    
    constructor() {
        super();
        this.state = {
          forecast: {}
        };
        this.setWeather = this.setWeather.bind(this);
      }
    
      getWeather () {
        let self = this;
        fetch('http://api.openweathermap.org/data/2.5/weather?zip=sl44jn,uk&units=metric&APPID=ed066f80b6580c11d8d0b2fb71691a2c')
          .then (function (response) {
            if (response.status !== 200) {
              console.log('Looks like there was a problem. Status Code: ' + response.status);
              return;
            }
            response.json().then(function(data) {  
            self.setWeather(data);
          });
        })
        .catch (function (err) {  
          console.log('Fetch Error :-S', err);
        });
      }
    
      setWeather (forecast) {
        this.setState({
          forecast: forecast
        });
      }
    
      componentWillMount() {
        this.getWeather();
      }
    
      render() {
        const { forecast } = this.state;
        return (
          <h1>{forecast.name}</h1>
        )
      }
    }
    

    【讨论】:

    • 天才先生。非常感谢。
    猜你喜欢
    • 2020-10-02
    • 2018-10-04
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多