簡體   English   中英

如何在 redux-thunk axios 異步中執行操作?

[英]how actions must be in redux-thunk axios async?

下午好

我是新手。 想使用 reacts,redux-thunk, axios, json-server 做一個 CRUD。

但我發現很難堅持一種正確的方式來處理動作

我有這個減速器:

import { types } from "../types/types";

const initialState = {
    data: null,
    deleted: null,
    error: ''
}

export const axiosDataReducer = (state = initialState, action) => {
    switch (action.type) {
        case types.get:
            return {
                ...state,
                data: action.data
            }
        case types.delete:
            return {
                ...state,
                deleted: action.deletedItem
            }

        case types.error:
            return {
                ...state,
                error: action.msg
            }
        default:
            return state;
    }
}

我有這個動作:

import axios from "axios";
import { baseURL } from "../json-server/baseURL"
import { types } from '../types/types'


// get data
export const fetchData = () => {
    return (dispatch) => {
        return axios.get(baseURL)
            .then(response => {
                return response.data
            })
            .then(data => {
                dispatch({
                    type: types.get,
                    data: data
                })
            })
            .catch(error => dispatch(
                {
                    type: types.error,
                    msg: "Unable to fetch data"
                }));
    };
};
//delete data
export const deleteData = (id) => {
    return (dispatch) => {
        return axios.get(`${baseURL}${id}`)
            .then(response => {
                return response.data
            })
            .then(data => {
                console.log(data)
                dispatch({
                    type: types.error,
                    deletedItem: data
                })
            })
            .catch(error => dispatch(
                {
                    type: types.error,
                    msg: "Unable to delete data"
                }));

    };
};

我有這個(表組件)組件,我在其中使用 useEffect 中的分派並工作,我獲取數據並在我的表中呈現數據,但我不知道為什么會這樣工作,是不是內部的雙重分派使用效果?:

import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { fetchData } from '../actions/actions';
import ButtonCreate from './buttons/ButtonCreate';
import ButtonDelete from './buttons/ButtonDelete';
import ButtonUpdate from './buttons/ButtonUpdate';

export default function Tabla() {
    const dispatch = useDispatch()
    const { data } = useSelector(state => state.axiosDataReducer)

    useEffect(() => {

        dispatch(fetchData())


    }, [])


    return (
        <div className='container mt-5 mb-5'>
            <ButtonCreate />
            <table className="table table-striped table-hover caption-top ">
                <caption>Online Store</caption>
                <thead className='table-dark'>
                    <tr className='text-center'>
                        <th scope="col">Id</th>
                        <th scope="col">Name</th>
                        <th scope="col">Cost</th>
                        <th scope="col">Category</th>
                        <th scope="col">Department</th>
                        <th scope="col">Update</th>
                        <th scope="col">Delete</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        data?.map((x, index) => (
                            <tr key={x.id}>
                                <th scope="col">{index + 1}</th>
                                <th scope="col">{x.name}</th>
                                <th scope="col">$ {x.cost.toFixed(2)}</th>
                                <th className='text-center'>
                                    {
                                        x.category.map((y, index) => (
                                            <span key={index * 0.125}>{y.name}</span>
                                        ))
                                    }
                                </th>
                                <th className='text-center'>
                                    {
                                        x.department.map((z, index) => (
                                            <span key={index * 0.225}>{z.name}</span>
                                        ))
                                    }
                                </th>
                                <th><ButtonUpdate /></th>
                                <th><ButtonDelete id={x.id} /></th>
                            </tr>
                        ))
                    }
                </tbody>
            </table>

        </div>
    )
}

在同一個表組件中,我想單擊刪除按鈕:

import React from 'react'
import { deleteData } from '../../actions/actions'

export default function ButtonDelete({ id }) {

    return (
        <div>
            <button
                className='btn btn-danger'
                onClick={deleteData(id)}
            >
                Delete
            </button>
        </div>
    )
}

,但是現在,對於前面的示例,它只會調度我指向的元素,console.log 工作正常,但是如果我嘗試調度我會收到此錯誤:

Unhandled Rejection (TypeError): dispatch is not a function

Uncaught (in promise) TypeError: dispatch is not a function

這是什么意思?

我想找出使用操作對服務器執行此異步請求的最基本方法。 我不知道為什么調度不能正常工作。

提前致謝,我很感激

您的deleteData() function 中有錯字。我相信您應該在調度類型中使用types.delete而不是types.error

此外,在您的Table組件中,您還必須使用useDispatch 因為,此掛鈎從必須傳遞給deleteData的 Redux 存儲返回對dispatch function 的引用。 您的onClick事件應該有一個返回調度的 function。 可能是這樣的:

<button
   className='btn btn-danger'
   onClick={() => dispatch(deleteData(id))}
>

您可能還想查看文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM