这个问题在这里已有答案:
我正在研究一个简单的Express/MongoDB/React
应用程序。
我尝试将从this.state.nearbyShops
中的API检索到的App.js
数组传递给组件NearbyShop
,以便可以显示它,但数组为null。它似乎没有从API中分配值(我确定API根据我的日志返回值)但它必须是我滥用的东西或引起这种情况的异步行为,我不知道它...
TypeError: Cannot read property 'map' of null
NearbyShop.render
C:/Users/yocalta/Documents/Projs/_rct/react-backend/client/src/NearbyShop.js:17
14 | //return <h1>Hello, {this.props.name}!</h1>;
15 | //console.log(this.props);
16 | var shops = this.props.shopsList;
> 17 | var cardShops = shops.map(function (shop) {
18 | return (
19 | <Card key={shop._id}>
20 | <CardImg top width="100%" src={shop.picture} alt="Card image cap" />
App.js
文件:
import React, { Component } from 'react';
import axios from 'axios';
import './App.css';
import NearbyShop from './NearbyShop';
class App extends Component {
constructor(props) {
super(props);
this.state = {
lat: 0,
long: 0,
nearbyShops: null
}
}
componentWillMount() {
var that = this;
// Get the user's location (lat & long) in the state object
const url = 'https://freegeoip.net/json/';
axios.get(url)
.then((response) => response.data)
// Get the long & lat of the end-user
.then((data) => that.setState({
lat: data.latitude,
long: data.longitude
}))
// Call our built-in Nearby API with the lat & long of the end-user
.then(function (data) {
axios.get('/nearby', {
params: {
lat: that.state.lat,
long: that.state.long
}
})
.then((response) => that.setState({
nearbyShops: response.shops
}))
.catch(function (error) {
console.log(error);
});
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div className="App">
<h1>Shops List</h1>
<NearbyShop shopsList={this.state.nearbyShops} />
</div>
);
}
}
export default App;
NearbyShop.js
文件:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {
Card, Button, CardImg, CardTitle, CardText, CardGroup,
CardSubtitle, CardBody
} from 'reactstrap';
class NearbyShop extends React.Component {
constructor(props) {
super(props);
this.state = {
shopsList: []
}
}
componentWillMount() {
//var shops = this.props.shopsList;
this.setState({ shopsList: this.props.shopsList});
}
render() {
//return <h1>Hello, {this.props.name}!</h1>;
//console.log(this.props);
//var shops = this.props.shopsList;
var cardShops = this.state.shopsList.map(function (shop) {
return (
<Card key={shop._id}>
<CardImg top width="100%" src={shop.picture} alt="Card image cap" />
<CardBody>
<CardTitle>{shop.name}</CardTitle>
<CardSubtitle>Card subtitle</CardSubtitle>
<CardText>{shop.email}</CardText>
<Button>Fall in love</Button>
</CardBody>
</Card>
);
})
return (
<CardGroup>
{cardShops}
</CardGroup>
);
}
}
export default NearbyShop;
nearByShops
的价值是null
,直到api
的结果出现。所以在第一次渲染时会抛出该错误。您可以通过向nearByShops
提供默认的空数组值来消除此错误。
constructor(props) {
super(props);
this.state = {
lat: 0,
long: 0,
nearbyShops: []
}
}
要么
你可以在迭代之前检查它的值是否存在。
// If value of shops exist, then only map through it
var cardShops = shops && shops.map(function (shop) {...