首页 > 解决方案 > 如何在反应中使用带有 API 调用的 redux?

问题描述

我很好奇如何将从 API 调用中找到的数据存储到 redux 存储中,然后访问它。这是我正在使用的代码。我不熟悉 redux,希望更好地了解如何使用它。

const mapStateToProps = state => {
  return {
    test: state.simpleReducer.test
  };
};

const mapDispatchToProps = dispatch => ({
  simpleAction: () => dispatch(simpleAction())
});

class App extends Component {
  weatherData = {};
  componentDidMount = () => {
    this.newAction();
  };

  newAction = async () => {
    let weatherResponse;

    await axios({
      method: "get",
      url: "http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${API_KEY}&units=metric"
    }).then(function(response) {
      weatherResponse = [...response.data];
    });
    this.weatherData = weatherResponse;
    console.log(this.weatherData);
  };

标签: javascriptreactjsapireduxaxios

解决方案


数据的来源并不重要——数据通过以该数据作为有效负载的分派操作进入您的存储,而化简器将该有效负载放入存储中。

因此,当您的请求完成时,您需要调度一个操作,并确保它在减速器中得到处理。

使用connectreact-redux 中的函数将您的 mapDispatchToProps 和 mapStateToProps 函数连接到您的组件,以便您可以发出操作并使用生成的更新状态。


推荐阅读