I am trying to refactor a Class component into a Function component in a react-redux app, but I am a bit stuck. When I try to convert this Component to a function Component, this line of code this.props.weather.map(this.renderWeather) no longer executes and it cannot read the list portion of code declared within the variables underneath the renderWeather() function
JavaScript
x
52
52
1
import React, {Component} from "react";
2
import { connect, useSelector } from "react-redux";
3
import Chart from "../containers/Chart";
4
5
6
class WeatherList extends Component {
7
renderWeather(results) {
8
const temp = results.list.map(weather => (weather.main.temp - 273.15) * 9/5 + 32);
9
const pressure = results.list.map(weather => weather.main.pressure);
10
const humidity = results.list.map(weather => weather.main.humidity);
11
12
13
return (
14
<tr key={results.city.id}>
15
<td>{results.city.name}</td>
16
<td>
17
<Chart color='yellow' data={temp} units='F'/>
18
</td>
19
<td>
20
<Chart color='green' data={pressure} units='hPa'/>
21
</td>
22
<td>
23
<Chart color='blue' data={humidity} units='%'/>
24
</td>
25
</tr>
26
)
27
}
28
29
render() {
30
return (
31
<table className="table table-hover">
32
<thead>
33
<tr>
34
<th>City</th>
35
<th>Temperature</th>
36
<th>Pressure</th>
37
<th>Humidity</th>
38
</tr>
39
</thead>
40
<tbody>
41
{ this.props.weather.map(this.renderWeather) }
42
</tbody>
43
</table>
44
)
45
}
46
}
47
48
function mapStateToProps({ weather }) {
49
return { weather }
50
}
51
52
export default connect(mapStateToProps)(WeatherList);
Advertisement
Answer
So it depends where you want to get the weather
data from.
- You could pass it as a prop
JavaScript
1
24
24
1
const WeatherList = (props) => {
2
3
return (
4
<table className="table table-hover">
5
<thead>
6
<tr>
7
<th>City</th>
8
<th>Temperature</th>
9
<th>Pressure</th>
10
<th>Humidity</th>
11
</tr>
12
</thead>
13
<tbody>
14
{props.weather.map(weatherItem => {
15
// contents of renderWeather
16
//
17
}
18
)}
19
</tbody>
20
</table>
21
)
22
23
}
24
- You could grab it from the Redux Store via
useSelector
JavaScript
1
7
1
const WeatherList = (props) => {
2
const weather = useSelector(store => store.pathInStore.weather);
3
//
4
// Continue as above
5
//
6
}
7
Note: You don’t have to do the renderWeather
inside the map as an anonymous function, it may be simpler to refactor it out to its own WeatherItem
component or something.