【问题标题】:unable to select items in object in react component无法在反应组件中选择对象中的项目
【发布时间】:2018-04-27 19:00:27
【问题描述】:

在我的 redux 操作中,我的 fetch 效果很好。我正在使用 redux-thunk 将它发送到我的减速器。然后我显然将我的组件连接到商店。在我的 reactjs 组件中,我能够看到 json 对象。假设结构是

object:{
    person: {
        name: {
            first: "first",
            last: "last"
    }
  }
}

当我尝试只获取像 (person.name.first) 这样的名字时,它会显示“TypeError: Cannot read property 'first' of undefined”,但 first 已定义。基本上任何三项深度的信息都会给我同样的信息。 在查看我的反应组件时,问题出在 console.log() 中。这个问题发生在组件内的任何地方,我尝试访问对象的相同位置,而不仅仅是在 console.log() 内。

我的行动:

import { WEEKWEATHER,
    TODAYWEATHER,
    SEARCH,
    LOCATIONERROR
} from './types';

//autolocate on page load
 export const autoLocate = (location) => {  
 const url = 
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' + 
 location + '.json'

 return (dispatch) => {

          fetch(url)
             .then((response) => response.json())
             .then(response => forcast(dispatch, response))
             .catch( (error) => { dispatch({ type:LOCATIONERROR }) })
};
};

//locate with search bar
 export const Locate = (location) => {  
 const url = 
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' + 
 location + '.json'

 return (dispatch) => {
 dispatch({type: SEARCH,
          payload: location
          });


          fetch(url)
            .then((response) => response.json())
            .then(response => forcast(dispatch, response))
            .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

};
};


//gathering forcast data from either auto or typed info
 const forcast = (dispatch, response) => {
 const location = response.location.zip
 const tenDayUrl = 
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/forecast10day/q/' 
 + location + '.json'
    const todayUrl = 
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/hourly/q/' + 
 location + '.json'

 fetch(todayUrl)
   .then((response) => response.json())
   .then(response => dispatch({
                               type: TODAYWEATHER,
                               payload: response.hourly_forecast[0]
                             }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })


   fetch(tenDayUrl)
     .then((response) => response.json())
     .then(response => dispatch({
                                 type: WEEKWEATHER,
                                 payload: 
 response.forecast.simpleforecast.forecastday[0]
                               }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })


 };

我的减速机:

import { TODAYWEATHER,  WEEKWEATHER, LOCATIONERROR, SEARCH } from 
'../Actions/types';

const INITIAL_STATE =  {
    week:[],
};
export default (state = INITIAL_STATE, action) => {
    switch (action.type){
        case WEEKWEATHER:
        return{ ...state, week:action.payload, loading:false }
                return state;
        }

    };

我的反应组件:

import React, { Component }     from 'react';
import { connect }              from 'react-redux';
import { Locate, autoLocate }   from '../Actions';
import {Card} from './Common'

class Weather extends Component{
    constructor(props){
        super(props);
        this.state={

         };
    }
    render() {
        const Loading = <Card>Loading...</Card>

        const Weather =  <div style={styles.PositionColumn}>
                            <div>tuesday</div>
                                <Card>
                                    <div style={styles.flexColumn}>
                                        <div style={styles.flexRow}>
                                            <div>jklsjdfkls</div>
                                            <div>2jlsfjle</div>
                                        </div>
                                        <div style={styles.flexRow}>
                                           <div>11</div>
                                            <div>22</div>
                                        </div>
                                    </div>
                                </Card>
                            </div>

        const displayWeather = (this.props.loading === true)? Loading 
: Weather;

        console.log(this.props.week.date.day)

        return(
           <div>
                <img style={styles.Background} src=
{this.state.background} alt=''/>


                    {displayWeather}

            </div>
        );
    }
}


const mapStateToProps = state => {
    const week = state.locate.week;


        return{ week };
}


export default connect(mapStateToProps, {Locate, autoLocate})(Weather)

【问题讨论】:

  • 您是否误删了冒号?人:{姓名:{第一个:“第一个”,最后一个:“最后一个”}}
  • 这没有帮助。您需要显示代码。您如何访问对象以及记录对象的位置?
  • 我很抱歉我应该在开始时添加我的代码。问题已更新为我遇到问题的代码
  • 不确定这是否只是一个示例,但我在您的代码中的任何地方都看不到 person.name.first

标签: javascript reactjs redux redux-thunk


【解决方案1】:

你需要用 reducer 初始化你的默认状态。

const INITIAL_STATE= {person : { name : {} }}

【讨论】:

    【解决方案2】:

    当 React 组件挂载时,redux 总是先发送 defaultState。 fetch 是否在componentWillMount 中并不重要。那个调度不够快。您需要在 reducer 文件中修复初始状态,使其具有与实际数据相同的模板。

    const INITIAL_STATE =  {
       person: {
         name: {
           first: "",
           last: ""
         }
       }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多