【问题标题】:React + Redux , error updating state using axiosReact + Redux ,使用 axios 更新状态时出错
【发布时间】:2020-09-04 11:27:35
【问题描述】:

我正在使用带有 Redux 的 React JS,我试图从 API 获取数据但遇到两个错误。

动作创建者: 下面的代码应该获取 API 数据并返回它。 我不知道如何返回获取的数据

import axios from 'axios';
const fetchlist = (id)=>{    
    const post = axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`).then(response=>response.data)

    return{

        type:'FETCH',
        payload:post.data
    }
}

export default fetchlist

减速器功能 下面的代码是更新 post 状态但得到 error Block is redundant no-lone-blocks

const post=(state={post:{}},action)=>{
switch(action.type){
    case 'FETCH':{    // ERROR OCCURES IN THIS LINE
        return { post:action.payload}
    };
    default: return state
}}

export default post

【问题讨论】:

  • 首先,您的fetchlist 操作创建者执行异步操作,因此您需要预先添加async (id) => {await axios.get(...)。其次,您需要像 redux-thunk 这样的东西来将异步性挂钩到 Redux 流程中。 stackoverflow.com/a/55683451/7956790
  • 谢谢,希望我学习一下 aync 动作

标签: javascript reactjs redux react-redux


【解决方案1】:

在 switch 语句中,在 return 之前删除大括号,它应该是:

case 'FETCH':
        return { post:action.payload}

【讨论】:

  • 该行周围的花括号实际上只是一个代码块。在此示例中不需要它们,因为案例中没有变量声明,但它们也不是问题的根源(甚至根本不是问题)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 2019-05-30
  • 1970-01-01
相关资源
最近更新 更多