反应 this.props 未定义或空对象

本文介绍了反应 this.props 未定义或空对象的处理方法,对大家解决问题具有一定的参考价值

问题描述

构建一个小型反应应用程序,将地理位置(由浏览器确定为作为道具的子组件)传递.

第一个组件:App.jsx

import React, {Component} from 'react';从'./components/dateTime/_dateTime.jsx'导入日期时间;从'./components/weather/_weather.jsx'导入天气;从'./components/welcome/_welcome.jsx'导入欢迎;要求('../sass/index.scss');导出默认类 App 扩展组件 {构造函数(){极好的();这个.state = {纬度:'',经度:''};this.showPosition = this.showPosition.bind(this);}启动应用程序(){this.getLocation();}获取位置(){if (navigator.geolocation) {navigator.geolocation.getCurrentPosition(this.showPosition);} 别的 {console.log("此浏览器不支持地理位置.");}}显示位置(位置){这个.setState({纬度:position.coords.latitude,经度:position.coords.longitude})}组件WillMount () {this.startApp();}使成为() {返回 (<div className="容器"><div className="header-container"><天气纬度={ this.state.latitude } 经度={ this.state.longitude }/><日期时间/></div><div className="欢迎容器"><欢迎名称="姓名"/></div></div>);}}

该组件确定位置,将纬度和经度保存到 state 并通过 props 将此信息传递给 Weather.jsx 组件,如下图所示:

在 weather.jsx 组件中,我尝试访问这些道具并获得未定义或空对象.

import React, {Component} from 'react';从'react-fetch'导入获取;导出默认类天气扩展组件 {构造函数(道具){超级(道具);这个.state = {预报: {},主要的: {},天气: {},};this.setWeather = this.setWeather.bind(this);}getWeather(纬度,经度){变种自我=这个;fetch('http://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&units=metric&APPID=ed066f80b6580c11d8d0b2fb71691a2c').then(函数(响应){如果(响应状态!== 200){console.log('看起来有问题.状态码:' + response.status);返回;}response.json().then(函数(数据) {self.setWeather(数据);});}).catch(函数(错误){console.log('获取错误:-S', err);});}设置天气(预测){var main = Forecast.main;var 天气 = Forecast.weather[0];这个.setState({主要:主要,天气:天气,预测:预测});}启动应用程序(){this.getWeather(this.props.latitude, this.props.longitude);}组件WillMount () {this.startApp();}组件DidMount () {//window.setInterval(function () {//this.getWeather();//}.bind(this), 1000);}使成为() {返回 (<div 类名=""><div className="天气数据"><span className="temp">{Math.round(this.state.main.temp)}°</span><h2 className="description">{this.state.weather.description}</h2></div></div>)}}

真的不确定问题是什么,因为 react 开发工具显示天气组件确实在传递给该组件的道具中设置了位置.

编辑**已解决:

所以问题是状态是异步设置的,并且我的天气组件是在状态更新之前呈现的.

在渲染方法期间对状态值的简单检查解决了这个问题.

render() {if (this.state.latitude != '' && this.state.longitude != '') {var weatherComponent = <天气纬度={ this.state.latitude } longitude={ this.state.longitude }/>} 别的 {var 天气组件 = 空;}返回 (<div className="容器"><div className="header-container">{天气组件}<日期时间/></div><div className="欢迎容器"><欢迎名称="姓名"/></div></div>);}

解决方案

我认为问题如下.SetState 异步发生.因此,您的渲染函数会在纬度和经度道具有数据之前触发.如果您在渲染 Weather 组件之前有一些 if 检查,您可能不会遇到此问题.这是我的意思的一个例子.

render() {让我的组件;if(检查 props 是否有 val) {我的组件 = <我的组件/>} 别的 {我的组件 = 空}返回 (
{我的组件}</div>)}

Building a small react app that passes the geolocation (determined by the browser to a child component as props).

The first component: App.jsx

import React, {Component} from 'react';

import DateTime from './components/dateTime/_dateTime.jsx';
import Weather from './components/weather/_weather.jsx';
import Welcome from './components/welcome/_welcome.jsx';

require ('../sass/index.scss');

export default class App extends Component {

  constructor() {
    super();
    this.state = {
      latitude: '',
      longitude: ''
    };
    this.showPosition = this.showPosition.bind(this);
  }

  startApp () {
    this.getLocation();
  }

  getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(this.showPosition);
    } else {
        console.log("Geolocation is not supported by this browser.");
    }
  }

  showPosition(position) {
    this.setState({
        latitude: position.coords.latitude,
        longitude: position.coords.longitude
    })
  }

  componentWillMount () {
    this.startApp();
  }

  render() {
    return (
        <div className="container">
            <div className="header-container">
                <Weather latitude={ this.state.latitude } longitude={ this.state.longitude } />
            <DateTime />
            </div>
            <div className="welcome-container">
                <Welcome name="Name" />
            </div>
      </div>
    );
  }
}

This component determines the location, saves the latitude and longitude to state and passes this information via props to the Weather.jsx component, which is working as you can see in the below image:

And in the weather.jsx component I try and access these props and get either undefined or an empty object.

import React, {Component} from 'react';
import Fetch from 'react-fetch';

export default class Weather extends Component {

    constructor(props) {
        super(props);
        this.state = {
          forecast: {},
          main: {},
          weather: {},
        };
        this.setWeather = this.setWeather.bind(this);
    }

    getWeather (latitude, longitude) {
        var self = this;

        fetch('http://api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&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) {
        var main = forecast.main;
        var weather = forecast.weather[0];

        this.setState({
            main: main,
            weather: weather,
            forecast: forecast
        });
    }

    startApp () {
        this.getWeather(this.props.latitude, this.props.longitude);
    }

    componentWillMount () {
        this.startApp();
    }

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

  render() {
    return (
        <div className="">
            <div className="weather-data">
                <span className="temp">{Math.round(this.state.main.temp)}°</span>
                <h2 className="description">{this.state.weather.description}</h2>
            </div>
        </div>
    )
  }
}

Really not sure what the issue is as the react dev tools shows that the weather component does indeed have the location set in the props which are passed down to that component.

Edit** Solved:

So the issue was that state is set asynchronously and that my weather component was rendered before state was updated.

A simple check of the values within state during the render method solved the issue.

render() {

    if (this.state.latitude != '' && this.state.longitude != '') {
      var weatherComponent = <Weather latitude={ this.state.latitude } longitude={ this.state.longitude } />
    } else {
      var weatherComponent = null;
    }

    return (
        <div className="container">
            <div className="header-container">
                {weatherComponent}
            <DateTime />
            </div>
            <div className="welcome-container">
                <Welcome name="Name" />
            </div>
      </div>
    );
  }

解决方案

I believe the issue is as follows. SetState happens asynchronously. Because of this, your render function is firing before the latitude and longitude props have data. If you would have some if check before rendering your Weather component you would likely not have this issue. Here is an example of what I mean.

render() {
    let myComponent;
    if(check if props has val) {
        myComponent = <MyComponent />
    } else {
        myComponent = null
    }
    return (
        <div>
            {myComponent}
        </div>
    )
}

这篇关于反应 this.props 未定义或空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1169

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1069

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this-&gt;id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:806

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this-&gt;id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:898

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:930

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:876

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:863

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:833

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1721

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1308