我正在使用 React/Redux 和 Rails API 创建一个基本的 CRUD 应用程序,当我在汽车表单上提交汽车时,我收到一条错误消息 - 但刷新浏览器会显示汽车。
我的 Cars.js 文件第 20 行出现错误: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
异步操作:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => {
try {
return response.json()
} catch(error) {
console.log(error);
}
})
.then(cars => {
dispatch(addCar([car]));
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}}
我不确定这里出了什么问题,因为应用程序在我重新加载后反射(reflect)了我的更改。最终,我试图在不刷新页面的情况下显示该信息。
最佳答案
问题是当你的组件安装时,它没有 cars 数组,而是有一个未定义的值。
发生这种情况是因为 getCars()
是异步的。
解决方案 1:向组件添加 defaultProp:
Component.defaultProps = {
cars: { cars: [] }
}
解决方案 2:
将汽车 key 添加到 reducer 的 initialState
initialState: { cars:{ cars:[] } }
关于reactjs - reducer Action 不动态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54772029/