Redux api 状态未在 nextjs 中更新

时间:2021-04-15 17:52:45

标签: javascript reactjs redux next.js

我有一个车辆表单组件,要求提供年份、品牌和型号。在用户选择年份后,我将调度一个 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>
        }

1 个答案:

答案 0 :(得分:0)

我没有更新状态并在同一个函数中调用它,而是使用了 e.target.value 并解决了问题。

//function called when a new year is selected
    const changeYear = (e) => {
        setYear(e.target.value);
        console.log(year)
        dispatch(loadMake({year: e.target.value}));
        setSelMake('Make');
    } 
相关问题