【问题标题】:Api is not hitting using react-reduxApi 没有使用 react-redux
【发布时间】:2020-09-13 10:10:10
【问题描述】:

user.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 从'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
   }
  }

用户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

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

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

 export default rootReducer

store.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

export * from './actions/blog'

我正在尝试使用 react-redux 获取数据,但 API 没有命中。我是 redux 的新手,只是想创建一个项目,但 API 并没有使用它。我不知道我错过了什么我还在 index.js 中提供了提供程序存储。任何帮助将不胜感激

【问题讨论】:

  • 我假设dispatch(fetchBlogRequest()) 也没有进入商店(那段代码是否被调用了?)?另外,由于您是 Redux 的新手,我建议您 a) 考虑使用 useSelectoruseDispatch 而不是 map 函数,这会使代码更加简洁明了。 b) 查看 Redux Toolkit,为您省去很多 Redux 的痛苦。
  • 有错误吗?该组件没有显示任何会阻止它分派操作的内容,也许您忘记了 Provider 或 thunk 中间件?
  • 控制台没有错误

标签: javascript reactjs redux react-redux


【解决方案1】:

您创建的fetchBlog fetchBlog 应该返回一个异步函数(也就是返回承诺的函数)

你刚刚错过了return

function fetchBlog(){
   return function(dispatch){

     dispatch(someAction());

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

或者你可以使用 async/await 函数

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

         const res = await axios.get();

         dispatch(setAction({ res }));

       }catch(error){

         dispatch(onErrorAction());
       }
    }
}

在 dispatch to props 函数中添加它,您不需要使用 dispatch 调用它,因为 thunk-middleware 将操作理解为函数并执行它,因此您只需要引用 thunk 本身你准备好了

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

或者更好,只使用一个对象

const mapDispatchToProps = {
    fetchBlog: fetchBlog
}

或者你可以

const mapDispatchToProps = {
    fetchBlog
}

这更简单

【讨论】:

  • 我发现你在地图内调度调度功能所以我更新了你的答案;)
猜你喜欢
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
  • 2017-09-18
  • 2020-11-19
  • 1970-01-01
  • 2020-03-13
  • 2019-02-21
相关资源
最近更新 更多