我正在使用带有Rails API的React / Redux创建一个基本的CRUD应用,当我在汽车表格上提交汽车时,我收到一条错误消息-但刷新浏览器会显示汽车。
错误在我的Cars.js文件的第20行显示clang x86-64 5.0 -std=c++11
:
Uncaught TypeError: Cannot read property 'map' of undefined
}
import React, { Component } from 'react';
import { connect } from 'react-redux';
import CarCard from '../components/CarCard';
import CarForm from './CarForm';
import './Cars.css';
import { getCars } from '../actions/cars';
class Cars extends Component {
componentDidMount() {
this.props.getCars()
}
render() {
return (
<div className="CarsContainer">
<h3>Cars Component</h3>
{this.props.cars.cars.map(car => <CarCard key={car.id} car={car} />)}
<CarForm />
</div>
);
}
这是我的const mapStateToProps = (state) => {
return ({
cars: state.cars
})
}
export default connect(mapStateToProps, { getCars })(Cars);
动作创建者:
createCar
还有我的const addCar = car => {
return {
type: 'CREATE_CAR_SUCCESS',
car
}}
异步操作:
createCar
我不确定这里出了什么问题,因为应用程序会在我重新加载后反映我的更改。最终,我试图显示这些信息而不必刷新页面。
答案 0 :(得分:1)
您要在异步操作将值置于状态之前进行渲染。如果尚未设置状态,请尝试从渲染返回null
:
render() {
if(!this.props.cars.cars){
return null;
}
return (
<div className="CarsContainer">
<h3>Cars Component</h3>
{this.props.cars.cars.map(car => <CarCard key={car.id} car={car} />)}
<CarForm />
</div>
);
}
换句话说,如果您的州没有要呈现的事物列表,则返回null-我认为上面的if可以工作,但是您可能想console.log("Cars in render", this.props.cars)
来看看你正在得到。
更好的选择IMO是将初始状态设置为this.props.cars
为[]
,这样就不必返回null且在render
中有特殊情况方法。我将需要查看您的reducer来建议如何执行该操作,但是如果您使其具有合理的默认/初始状态,则应该能够轻松地做到这一点。
答案 1 :(得分:1)
问题在于,当您安装组件时,它没有cars数组,而是具有未定义的值。
发生这种情况是因为getCars()
是异步的。
解决方案1::向组件添加defaultProp:
Component.defaultProps = {
cars: { cars: [] }
}
解决方案2:
将汽车钥匙添加到减速器的initialState
initialState: { cars:{ cars:[] } }
答案 2 :(得分:1)
您正在componentDidMount中进行动作调用getCars,并且此生命周期方法在首次渲染后被调用,因此在初始渲染时,此props.cars将是未定义的
如果您正在获得this.props.cars之类的
{
“cars”: [....]
}
然后您需要在访问汽车对象之前进行条件检查
更改
{this.props.cars.cars.map(car => <CarCard key={car.id} car={car} />)}
收件人
{this.props.cars && this.props.cars.cars.map(car => <CarCard key={car.id} car={car} />)}