我正在开发一个CRUD应用程序,必须更新我的地址和PIN码。我正在尝试使用Redux用获取的数据更新地址,但总是得到“ TypeError:无法读取未定义的属性'address'”我不知道代码有什么问题,因为相同的代码会更新City
字段。
EditLocation.js
const EditLocation = ({
location: { location, loading },
editLocation,
getCurrentLocation,
history,
match
}) => {
const [formData, setFormData] = useState({
address: "",
pinCode: ""
});
useEffect(() => {
getCurrentLocation(match.params.id);
setFormData({
address: loading || !location.address ? "" : location.address, // i am getting error here code cant define location.adress
pinCode: loading || !location.pinCode ? "" : location.pinCode
});
}, [loading, getCurrentLocation]);
const onChangeHandler = e => {
e.preventDefault();
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const onSubmitHandler = e => {
e.preventDefault();
editLocation(formData, history, match.params.id);
};
return (
<div>
</div>
)}
EditLocation.propTypes = {
editLocation: PropTypes.func.isRequired,
getCurrentLocation: PropTypes.func.isRequired,
location: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
location: state.location
});
// alert(JSON.stringify(location.address));
export default connect(
mapStateToProps,
{ editLocation, getCurrentLocation }
)(withRouter(EditLocation));
LocationAction.js
// Get current location
export const getCurrentLocation = id => async dispatch => {
try {
const res = await axios.get(`/api/location/${id}`);
console.log(res.data.data.address);
dispatch({
type: types.GET_LOCATION,
payload: res.data
});
} catch (err) {
dispatch({
type: types.LOCATION_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
});
}
};
locationReducer.js
import * as types from "../../_actions/types";
const initialState = {
location: null,
locations: [],
error: {},
filtered: null,
loading: true
};
export default function(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case types.GET_LOCATION:
return {
...state,
location: payload,
loading: false
};
default:
return state;
}
}
但是,当我使用Postman时,它工作正常,并且locationAction.js中的console.log(res.data.data.address);
也会显示获取的数据,但是当我单击更新按钮时,它会显示TypeError。
我重复了相同的代码,当我想更新City
字段时,它工作正常。