繁体   English   中英

Redux api state 未在 nextjs 中更新

[英]Redux api state not updating in nextjs

我有一个要求年份、制造商和 model 的车辆形式组件。 在用户选择年份后,我将发送一个 redux 操作以获取该年的所有品牌,然后在选择一个品牌后,我将发送一个操作以获取该品牌的所有模型。

到目前为止,当我 select 这一年我可以看到 api 被调用,但 state for make 没有在 console.log 或页面上更新。 如果我 select 不同年份,则再次调用 api 并且第一次调用的生成列表显示在页面上。

我尝试将 mapstatetoprops 放在页面中并将其作为 state 传递给 vehicleForm 组件,并直接在车辆表单中调用 mapstatetoprops,但没有任何改变。

动作.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
            })
        })
}

减速器.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 并在同一个 function 中调用它,而是使用了 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');
    } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM