首页 > 解决方案 > 在 reducer 中更改状态后组件未更新

问题描述

我想向我的用户显示错误。一个错误被抛出并且错误和消息在reducer中被action更新。但由于某种原因,我无法为用户显示错误或消息。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);

标签: reactjsreduxreact-reduxreact-thunk

解决方案


在您的 CREATE_VEHICLE 操作中,我认为您的意思是用大括号返回状态?{...state, Object.assign({}, action.vehicle, action.message)}

在您的 mapStateToProps 中,您尝试访问state.vehiclesand 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 的更改进行更新。


推荐阅读