【发布时间】:2021-04-15 17:52:45
【问题描述】:
我有一个询问年份、品牌和型号的车辆表单组件。在用户选择年份后,我将发送一个 redux 操作以获取该年份的所有品牌,然后在选择一个品牌后,我将发送一个操作以获取该品牌的所有模型。
到目前为止,当我选择年份时,我可以看到调用了 api,但 make 的状态在 console.log 或页面上没有更新。如果我选择不同的年份,则会再次调用该 api,并在页面上显示第一次调用的制造商列表。
我尝试将 mapstatetoprops 放入页面并将其作为状态传递给 vehicleForm 组件,并在车辆表单中直接调用 mapstatetoprops,但没有任何改变。
actions.js
export const loadMake = (data) => async (dispatch, getState) => {
//vehicle Loading
dispatch({type: MAKE_LOADING})
await axios
.post(`${keys.redirectDomain}/api/vehicle/getMake`, data)
.then(res => dispatch({
type: VEHICLE_MAKE,
payload: res.data,
}))
.catch(err => {
// dispatch(returnErrors(err.response, err.response))
dispatch({
type: VEHICLE_ERROR,
payload: err.response
})
})
}
reducers.js
const Vehicle = (state = INIT_STATE, action = {}) => {
switch (action.type) {
case VEHICLE_LOADING:
return {...state, loading: true};
case MAKE_LOADING:
return {...state, makeLoading: true, make: []};
case MODEL_LOADING:
return {...state, modelLoading: true, model: []};
case VEHICLE_MAKE:
return {...state, loading: false, makeLoading: false, make: action.payload};
case VEHICLE_MODEL:
return {...state, loading: false, modelLoading: false, model: action.payload};
case VEHICLE_ERROR:
return {...state, loading: false, error: action.payload};
default:
return state;
}
}
来自 vehicleform.js 的函数
//function called when a new year is selected
const changeYear = (e) => {
setYear(e.target.value);
console.log(year)
dispatch(loadMake({year: year}));
setSelMake('Make');
}
//part of component where data is displayed
{modelLoading &&
<CircularProgress />
}
{!modelLoading &&
<FormControl>
<Select value={selModel} onChange={changeModel}>
<MenuItem value={type}>{type}</MenuItem>
{model.map((item, index) => (
<MenuItem key={index} value={item}>{item}</MenuItem>
))}
</Select>
</FormControl>
}
【问题讨论】:
-
想通了,state/setYear 在调度到 loadMake 之前没有更新。我将其切换为 dispatch(loadMake({year: e.target.value})
-
您可能希望添加您的解决方案作为您自己问题的答案,以表明它已被解决。
标签: javascript reactjs redux next.js