reactjs - 在 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);
解决方案
在您的 CREATE_VEHICLE 操作中,我认为您的意思是用大括号返回状态?{...state, Object.assign({}, action.vehicle, action.message)}
在您的 mapStateToProps 中,您尝试访问state.vehicles
and 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 的更改进行更新。
推荐阅读
- apache-spark - 运行 spark-shell 会导致“连接被拒绝”
- c# - 反斜杠在 WebGet 中未被识别为参数
- github - 如何在 Visual Studio 中使用“make”解决此问题
- google-cloud-platform - kafka 消费者是否管理其状态?
- c# - c# 从listview查询rdlc报告
- oracle - 当顺序(序号)和列长已知时如何推导列的开始和结束位置
- c# - 如何将程序集绑定配置添加到 Azure 函数?
- google-apps-script - Google 云端硬盘 - 导入工作表
- exoplayer - 如何让变形视频与 exoplayerleaback 一起使用?
- python - 在另一个函数中调用一个函数