componentwillmount () Неперехваченная ошибка: Действия должны быть простыми объектами. Используйте настраиваемое промежуточное ПО для асинхронных c действий - PullRequest
0 голосов
/ 11 июля 2020

Я реализую получение всех изображений по типам с помощью redux-saga. У меня есть 2 типа, скажем, тип кристик и типовой мотив. Когда я реализую тип kristik, он получил успешный ответ, но когда дело доходит до типа motif, ответ - ошибка.

здесь мой код с ошибкой в ​​консоли

    componentWillMount() => {
        const { dispatch } = this.props;

        dispatch(getAllMotif());
    }

У меня ошибка dispatch(getAllMotif()); в commponentWillMount()

Здесь мой getAllMotif() код

    getAllMotif(token) {
        const path = `motif`;
        const method = 'get';

        return request.process(method, path, null, token);
    },

Здесь мой sagas getAllMotif код

export function* getAllMotif() {
    try {
        let { detail } = yield select(state => state.user);

        const result = yield call(API.getAllMotif, detail.api_token);
        yield put({
            type: types.GET_ALL_MOTIF_SUCCESS,
            payload: result,
        });
    } catch (err) {
        yield put(handleError(err));

        yield put({
            type: types.GET_ALL_MOTIF_FAILURE,
            payload: err,
        });
    }
}

здесь мой редуктор

            case types.GET_ALL_MOTIF_SUCCESS:
            return {
                ...state,
                motif: [
                    ...action.payload.data.data
                ]
            };  

вот мой код запроса

internals.process = (method, path, payload, token, contentType=internals.contentType) => {
    const request = {
        url: `${API_URL}/${path}`,
        method: method,
        headers: {
            'Content-Type': contentType,
            'Accept': 'application/json',
        },
    };

    if (token) {
        request.params = {
            token: token,
        };
    }

    if (payload) {
        request.data = payload;
    }

    return axios.request(request)
        .then(res => {
            if (![200, 201].includes(res.status)) {
                throw new Error(res.status);
            }

            return res.data;
        })
        .catch((error) => {
            console.error(method, path, error);
            return Promise.reject({
                message: error.response.data.error,
                code: error.response.status
            });
        });
};

Я не знаю, почему в этом типе появляется ошибка, потому что в типе kristik также очень похожий код.

1 Ответ

0 голосов
/ 11 июля 2020

Вы не отправили действие, которое не было простым объектом, ваша функция getAllMotif не вернула простой объект. Это приводит к ошибке здесь.

Вы должны отправить обычное действие

getAllMotifAction(token) {
    const path = `motif`;
    const method = 'get';

    return { type: 'GET_ALL_MOTIF', data: { path, method } };
},

Затем в саге вы поймаете это действие и обработаете его с помощью своей функции саги

takeLatest('GET_ALL_MOTIF', getAllMotif);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...