首页 > 解决方案 > 反应改变与后端的连接以使用@cparram/use-redux-api

问题描述

我正在创建一个反应应用程序,我被要求使用这个库 np​​m i @cparram/use-redux-api 将前端连接到后端。我是新来的反应,不明白如何改变我的连接。

这是我从数据库中获取数据的 ActionCreators

import  * as ActionTypes from './ActionTypes';
import { baseUrl } from '../shared/baseUrl';

export const addComment = (comment) => ({
    type: ActionTypes.ADD_COMMENT,
    payload: comment
});

export const postComment = (postId, email, name, body) => (dispatch) => {

    const newComment = {
        postId: postId,
        email: email,
        name: name,
        body: body
    };

    return fetch(baseUrl + 'comments', {
        method: "POST",
        body: JSON.stringify(newComment),
        headers: {
          "Content-Type": "application/json"
        },
        credentials: "same-origin"
    })
    .then(response => {
        if (response.ok) {
          return response;
        } else {
          var error = new Error('Error ' + response.status + ': ' + response.statusText);
          error.response = response;
          throw error;
        }
      },
      error => {
            throw error;
      })
    .then(response => response.json())
    .then(response => dispatch(addComment(response)))
    .catch(error =>  { console.log('post comments', error.message); alert('Your comment could not be posted\nError: '+error.message); });
};


export const addNewPost = (post) => ({
    type: ActionTypes.ADD_POST,
    payload: post
});

export const postNewPost = (userId, id, title, body) => (dispatch) => {

    const newPost = {
        userId: userId,
        id: id,
        title: title,
        body: body
    };

    return fetch(baseUrl + 'posts', {
        method: "POST",
        body: JSON.stringify(newPost),
        headers: {
          "Content-Type": "application/json"
        },
        credentials: "same-origin"
    })
    .then(response => {
        if (response.ok) {
          return response;
        } else {
          var error = new Error('Error ' + response.status + ': ' + response.statusText);
          error.response = response;
          throw error;
        }
      },
      error => {
            throw error;
      })
    .then(response => response.json())
    .then(response => dispatch(addNewPost(response)))
    .catch(error =>  { console.log('post new Post', error.message); alert('Your Post could not be posted\nError: '+error.message); });
};


export const fetchPosts = () => (dispatch) => {
    dispatch(postsLoading(true));

    return fetch(baseUrl + 'posts')
        .then(response => {
            if(response.ok) {
                return response;
            }else{
                var error = new Error('Error' + response.status +': '+response.statusText);
                error.response = response;
                throw error;
            }
        },
        error => {
            var errmess = new Error(error.message);
            throw errmess;
        })
        .then(response => response.json() )
        .then(posts => dispatch(addPosts(posts)))
        .catch(error => dispatch(postsFailed(error.message)));
}

export const postsLoading = () => ({
    type:ActionTypes.POSTS_LOADING
});

export const postsFailed = (errmess) => ({
    type:ActionTypes.POSTS_FAILED,
    payload:errmess
});

export const addPosts = (posts) => ({
    type:ActionTypes.ADD_POSTS,
    payload:posts
});

export const fetchComments = () => (dispatch) => {
    return fetch(baseUrl + 'comments')
        .then(response => {
            if(response.ok) {
                return response;
            }else{
                var error = new Error('Error' + response.status +': '+response.statusText);
                error.response = response;
                throw error;
            }
        },
        error => {
            var errmess = new Error(error.message);
            throw errmess;
        })
        .then(response => response.json() )
        .then(comments => dispatch(addComments(comments)))
        .catch(error => dispatch(commentsFailed(error.message)));
}

export const commentsFailed = (errmess) => ({
    type:ActionTypes.COMMENTS_FAILED,
    payload:errmess
});

export const addComments = (comments) => ({
    type:ActionTypes.ADD_COMMENTS,
    payload:comments
});

我尝试了各种方法来做到这一点,但得到了很多错误。我完全迷失了。

当我尝试使用此代码获取帖子时:

export const fetchPosts = () => (dispatch) => {
    dispatch(postsLoading(true));

const [api, apiCall] = useReduxApi('redux-store-key')

    return useEffect(() => {
    apiCall({ endpoint: 'https://jsonplaceholder.typicode.com/posts' })
  }, []).then(response => {
            if(response.ok) {
                return response;
            }else{
                var error = new Error('Error' + response.status +': '+response.statusText);
                error.response = response;
                throw error;
            }
        },
        error => {
            var errmess = new Error(error.message);
            throw errmess;
        })
        .then(response => response.json() )
        .then(posts => dispatch(addPosts(posts)))
        .catch(error => dispatch(postsFailed(error.message)));
}

我收到这个错误

错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一: 1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能有多个 React 副本同一个应用

标签: reactjsapi

解决方案


推荐阅读