简体   繁体   English

Api 没有使用 react-redux

[英]Api is not hitting using react-redux

user.js用户.js

import React, { useEffect } from 'react';
import { fetchBlog } from '../../redux';
import { connect } from 'react-redux'

const Home = ({ blogData, fetchBlog }) => {
const { id } = useParams();
useEffect(() => {
    fetchBlog();
}, []);

return (
    <>
        <div className="container">
            <div className="col-lg-10">
                <h2> React CRUD Operation </h2>
            </div>
            <div className="col-lg-2">
                <Link to="/add" >
                    <button> Add Blog </button>
                </Link>
            </div>
            <table className="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Picture</th>
                        <th>Title</th>
                        <th>Short Description</th>
                        <th>Author</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    {blogData.map((it) => {
                        return (
                            <tr key={it.id}>
                                <td> {it.id} </td>
                                <td> {<img src={it.pic} alt="not available" />} </td>
                                <td> {it.title} </td>
                                <td> {it.short_desc} </td>
                                <td> {it.author} </td>

                    })}
                </tbody>
            </table>
           
    </>
 )
}

const mapStateToProps = state => {
 return {
  blogData: state.blog
 }
}

const mapDispatchToProps = dispatch => {
 return {
    fetchBlog: () => dispatch(fetchBlog())
 }
}

 export default connect (
   mapStateToProps,
   mapDispatchToProps
 ) (Home)

userAction.js import axios from 'axios' userAction.js 从 'axios' 导入 axios

export const fetchBlog = () => {
return (dispatch) => {
dispatch(fetchBlogRequest())
axios
  .get('http://localhost:3001/api/blog/get')
  .then(response => {
    const blog = response.data
    dispatch(fetchBlogSuccess(blog))
  })
  .catch(error => {
    // error.message is the error message
    dispatch(fetchBlogFailure(error.message))
  })
  }
 }

export const fetchBlogRequest = () => {
 return {
  type: 'FETCH_BLOGS_REQUEST'
 }
}

 export const fetchBlogSuccess = blogs => {
  return {
   type: 'FETCH_BLOGS_SUCCESS',
   payload: blogs
  }
 }

 export const fetchBlogFailure = error => {
  return {
    type: 'FETCH_BLOGS_FAILURE',
    payload: error
   }
  }

user reducer.js用户 reducer.js

const initialState = {
 loading: false,
 blogs: [],
 error: ''
}

const BlogsReducer = (state = initialState, action) => {
 switch (action.type) {
    case 'FETCH_BLOGS_REQUEST':
        return {
            ...state,
            loading: true
        }
    case 'FETCH_BLOGS_SUCCESS':
        return {
            loading: false,
            blogs: action.payload,
            error: ''
        }
    case 'FETCH_BLOGS_FAILURE':
        return {
            loading: false,
            blogs: [],
            error: action.payload
        }
    default: return state
 }
}

export default BlogsReducer

rootReducer.js rootReducer.js

  import  { combineReducers } from 'redux'
  import BlogReducer from './reducer/blog'

 const rootReducer = combineReducers({
  blog: BlogReducer
 });

 export default rootReducer

store.js商店.js

import { createStore, applyMiddleware } from 'redux'
import rootReducer from './rootReducer'
import thunk from 'redux-thunk';

const store = createStore(
 rootReducer,
 applyMiddleware(thunk)
);

export default store

index.js索引.js

export * from './actions/blog'

I am trying to fetch data using react-redux but API is not hitting.我正在尝试使用 react-redux 获取数据,但 API 未命中。 I am new to redux and just trying to make a project but API is not hitting using this.我是 redux 的新手,只是想制作一个项目,但 API 并没有使用它。 I don't know what I am missing I have also provided provider store in index.js.我不知道我错过了什么我还在 index.js 中提供了提供程序存储。 Any help will be appreciated任何帮助将不胜感激

the thunk you made fetchBlog should return an async function(aka a function that return a promise)thunk你做fetchBlog应该返回一个异步函数(又名返回一个承诺的函数)

you just missed the return你只是错过了return

function fetchBlog(){
   return function(dispatch){

     dispatch(someAction());

     return axios.get()
            .then(() => {
                dispatch(setAction());
            })
            .catch(error => {
                dispatch(onErrorAction());
            });
   }
}

or you can use async/await functions或者你可以使用 async/await 函数

function fetchBlog(){
    return async (dispatch) => {
       try{
         dispatch(someAction());

         const res = await axios.get();

         dispatch(setAction({ res }));

       }catch(error){

         dispatch(onErrorAction());
       }
    }
}

add to that in dispatch to props function you don't need to call it with dispatch because the thunk-middleware understand action as function and it go execute it, so you just need to have a reference to the thunk itself and you are ready在 dispatch to props 函数中添加,你不需要用 dispatch 调用它,因为thunk-middleware动作理解为函数并执行它,所以你只需要引用thunk本身就可以了

const mapDispatchToProps = dispatch => {
 return {
    fetchBlog: fetchBlog
 }
}

or better, just use an object或者更好,只使用一个对象

const mapDispatchToProps = {
    fetchBlog: fetchBlog
}

or you can或者你可以

const mapDispatchToProps = {
    fetchBlog
}

which is even simpler这更简单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM