【问题标题】:Difficulties creating an action that fetches data with React Redux and axios难以创建使用 React Redux 和 axios 获取数据的操作
【发布时间】:2020-12-11 19:18:33
【问题描述】:

我利用这个周末来学习 Redux,但我不明白如何使用 axios、Redux 和 Redux Thunk 进行 API 调用强>

我已删除此示例项目中的所有内容,因此只有一个操作:我要从中获取数据的操作。

Here's the link to my codesandbox

我确定我错过了一些非常简单的东西,但我不知道它是什么。 如果有人可以帮助我或为我指明正确的方向,我将不胜感激

我的减速机

const initialState = {
  data: [],
};

const reducer = (state = initialState, action) => {
  const newState = { ...state };

  switch (action.type) {
    case 'SOMETHING':
      newState.data = action.data;
      console.log(newState.data);
      break;
    default:
      newState;
  }
  return newState;
};

export default reducer;

我的行动

import axios from 'axios';

export function someFunction() {
  return (dispatch) => {
    axios.get('https://api.pokemontcg.io/v1/types').then((response) => {
      dispatch({ type: 'SOMETHING', data: response.data });
    });
  };
}

我的 App.js

function App({ someFunction }) {
  return (
    <div className="App">
      <button onClick={someFunction}>Click Me</button>
    </div>
  );
}

const mapStateToProps = (state) => {
  return {
    data: state.data,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    something: () => dispatch(actionCreator.someFunction()),
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(App);

【问题讨论】:

  • 您需要将 name 引用为您在 mapDispatchToProps 中返回的内容,而不是实际的动作创建函数名称。

标签: reactjs redux react-redux axios redux-thunk


【解决方案1】:

你快到了!问题就在这里:

const mapDispatchToProps = (dispatch) => {
  return {
    something: () => dispatch(actionCreator.someFunction()),
  };
};

您告诉 redux 将 dispatch 操作映射到名为 { something } 的道具。您需要将道具重命名为something 或将地图重命名为someFunction。

const mapDispatchToProps = (dispatch) => {
  return {
    someFunction: () => dispatch(actionCreator.someFunction()),
  };
};

【讨论】:

  • @ItzaMi,上面的一个小补充,带有object short hand 符号,const mapDispatchToProps = { someFunction: actionCreator.someFunction };。您可以像这样声明简单的操作。查看here了解更多详情
  • 谢谢@Cehhiro,我不敢相信我没有看到。今天是我第一次接触 Redux,概念太多了,但感谢您的快速回复!
  • 我有一个新问题,@Cehhiro。如何在页面加载时通过初始调用 axios 填充我的状态?
猜你喜欢
  • 2018-11-14
  • 1970-01-01
  • 2022-11-01
  • 2020-07-25
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 1970-01-01
  • 2022-01-04
相关资源
最近更新 更多