Javascript 类型错误:this.props.weather未定义
我正在开发一个应用程序,它将帮助我使用openweathermap.org获取任何城市的五天天气预报,然而,每当我调用WeatherList容器中的函数renderWeather时,我都会在浏览器中出现上述错误,如下面的代码片段所示 这个文件就是我导入redux promise的index.jsJavascript 类型错误:this.props.weather未定义,javascript,reactjs,redux,react-redux,redux-promise,Javascript,Reactjs,Redux,React Redux,Redux Promise,我正在开发一个应用程序,它将帮助我使用openweathermap.org获取任何城市的五天天气预报,然而,每当我调用WeatherList容器中的函数renderWeather时,我都会在浏览器中出现上述错误,如下面的代码片段所示 这个文件就是我导入redux promise的index.js 从“React”导入React; 从“react dom”导入react dom; 从'react redux'导入{Provider}; 从“redux”导入{createStore,applyMi
从“React”导入React;
从“react dom”导入react dom;
从'react redux'导入{Provider};
从“redux”导入{createStore,applyMiddleware};
从“redux承诺”导入redux承诺;
从“./components/App”导入应用程序;
从“./reducers”导入减速机;
const createStoreWithMiddleware=applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
,document.querySelector('.container')
这是因为这个.props.weather
是未定义的
,因此在未定义的
上调用.map()
函数将抛出错误。您可以提前添加验证,以确保它仅在作为数组时调用.map()
(当数据进入时)
您可以添加:
Array.isArray(this.props.weather) && ...
在此处进行更改:
import React,{Component}来自'React';
从'react redux'导入{connect};
类天气列表扩展组件{
渲染天气(城市数据){
返回(
{cityData.city.name}
);
}
render(){
返回(
城市
温度
压力
湿度
{Array.isArray(this.props.weather)&&this.props.weather.map(this.renderWeather)}
);
}
}
函数MapStateTops(状态){
返回{
天气:state.weather
};
}
导出默认连接(MapStateTops)(天气列表)代码>最初this.props.weather将是未定义的,因此您需要在执行.map-like之前通过两种方式执行条件检查
this.props.weather && this.props.weather.map
或
另外,在执行.map时,您需要将天气数据传递给renderWeather方法,因为它需要数据,但您没有在.map中将数据传递给它
改变
{this.props.weather.map(this.renderWeather)}
到
也可以在此处设置tr元素的唯一键
renderWeather(cityData){
return(
<tr key={cityData.city && cityData.city.id}> //if you do not have unique id then use index as key
<td>{cityData.city && cityData.city.name}</td>
</tr>
);
}
renderWeather(cityData, index){
return(
<tr key={"city-"+index}> //if you do not have unique id then use index as key
<td>{cityData.city && cityData.city.name}</td>
</tr>
);
}
也可以在此处设置tr元素的唯一键
renderWeather(cityData){
return(
<tr key={cityData.city && cityData.city.id}> //if you do not have unique id then use index as key
<td>{cityData.city && cityData.city.name}</td>
</tr>
);
}
renderWeather(cityData, index){
return(
<tr key={"city-"+index}> //if you do not have unique id then use index as key
<td>{cityData.city && cityData.city.name}</td>
</tr>
);
}
renderWeather(城市数据,索引){
返回(
//如果您没有唯一的id,则使用索引作为键
{cityData.city&&cityData.city.name}
);
}
在WeatherList中,您可以尝试{this.props.weater&&this.props.weather.map(..
您的代码当您有未定义的变量时,这不会导致执行代码
renderWeather(cityData, index){
return(
<tr key={"city-"+index}> //if you do not have unique id then use index as key
<td>{cityData.city && cityData.city.name}</td>
</tr>
);
}