[英]Component not being updated after state is changed in reducer
我想向用戶顯示錯誤。 動作將引發錯誤,並在化簡器中更新錯誤和消息。 但是由於某種原因,我無法為用戶顯示錯誤或消息。 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);
在您的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更改時進行更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.