繁体   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