簡體   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