我想向用户显示错误。动作将引发错误,并在化简器中更新错误和消息。但是由于某种原因,我无法为用户显示错误或消息。 reducer或mapStateToProps有问题吗?组件如何知道状态已更新?我不确定如何更新它。
我想念什么?
减速器:
import {CREATE_VEHICLE,VEHICLE_ERROR,
VEHICLE_FORM_PAGE_SUBMIT,FETCH_VEHICLES_SUCCESS} from '../actions/vehicles';
const initialState={message: null, error: null, vehicle:{}};
export default function vehicleReducer(state=initialState, action) {
console.log("in reducer");
switch(action.type){
case CREATE_VEHICLE:
return [...state, Object.assign({}, action.vehicle, action.message)];
case VEHICLE_ERROR:
return{
...state,
error: action.error,
message: action.message
};
default:
return state;
}
}
动作:
export const vehicleError = (error, msg) => {
return{
type: VEHICLE_ERROR,
error:error,
message: msg
}
};
export const createVehicle=(vehicle) =>{
console.log("vehicle: ", vehicle);
return (dispatch) => {
return axios.post(`http://localhost:9081/api/bmwvehicle/create`,
vehicle)
.then((response) =>{
if (response.ok){
console.log("success");
dispatch(createVehicleSuccess(response.data))
}}, (error) => {
if (error.response.status == 500){
dispatch(vehicleError(error.message, "Could not add vehicle,
please try again."));
}
}
);
};};
组件:
class Vehicle extends React.Component{
constructor(props){
super(props);
}
submitVehicle(input){
this.props.createVehicle(input);
}
render(){
console.log("the error is: ",this.props.error);
return(
<div>
<AddVehicle submitVehicle=
{this.submitVehicle.bind(this)} />
</div>
)
}
}
const mapStateToProps=(state, ownProps) => {
return{
vehicle: state.vehicle,
message: state.message,
items: state.items,
vehicles: state.vehicles,
error: state.error
}
};
const mapDispatchToProps=(dispatch)=>{
return {
createVehicle: vehicle =>
dispatch(vehicleActions.createVehicle(vehicle))
}
};
export default connect(mapStateToProps, mapDispatchToProps)(Vehicle);
答案 0 :(得分:0)
在您的CREATE_VEHICLE动作中,我认为您是要用花括号将状态返回? {...state, Object.assign({}, action.vehicle, action.message)}
在mapStateToProps中,您尝试访问state.vehicles
和state.items
,但是在默认的初始状态const initialState={message: null, error: null, vehicle:{}}
中不存在。
要回答有关组件如何知道(redux)状态已被更新的问题,组件知道是因为您将其包装在称为connect()的Redux HoC中,它将在映射的redux状态下通过更新通知组件变化。对于您而言,该组件将根据Redux存储的state.vehicle,state.message,state.items,state.vehicles和state.error的更改进行更新。