【问题标题】:How to fetch using axios when the api comes from a state via reducer?当api通过reducer来自状态时如何使用axios获取?
【发布时间】:2017-08-06 08:59:18
【问题描述】:

我想从减速器返回的状态中获取一个 api。 这是我的容器:PokeDetailApi.js

import React, {Component} from "react";
import {connect} from "react-redux";
import axios from "axios";

class PokeDetailApi extends Component{
    constructor(){
        super();
        this.state = {
            pokedetails:""
        }
    }

    componentDidMount(){
        axios.get({this.props.pokemon.url}).then( (obj) => {
            this.setState({
                pokedetails: obj.data.results
            });
        });
    }

    render(){
        if(!this.props.pokemon){
            return (
                <div>
                    <h1>Please select a pokemon.</h1>
                </div>
            )
        }

        // const url = this.props.pokemon.url;
        const urlapi = this.state.pokedetails;

        console.log(url);
        console.log(urlapi);

        return(
            <div>
                <p>{this.props.pokemon.name}</p>
            </div>
        )
    }
}

function mapStateToProps(state){
    return {
        pokemon: state.selected_pokemon
    }
}

export default connect(mapStateToProps)(PokeDetailApi);

{this.props.pokemon.url} 返回特定 pokemon 的 url。我想使用此处找到的该 url 显示该 pokemon 的所有详细信息:https://pokeapi.co/

这是reducer返回的对象:

{
    name:"bulbasaur"
    url:"http://pokeapi.co/api/v2/pokemon/1/"
}

使用 axios 从 reducer 从 api 访问对象的正确方法是什么?

【问题讨论】:

    标签: javascript reactjs redux axios


    【解决方案1】:

    您说的是减速器,但直接在您的组件中调用 fetch.. 您应该调用一个执行获取的操作。

    除此之外,您还可以在您的 .then 中执行另一个提取,而不是在您的渲染中使用第一次提取的结果(pokedetails):

    axios.get(this.props.pokemon.url)
      .then(res => res.data.results)
      .then(axios.get) // fetch on pokedetails
      .then(console.log) // console.log result, here you could setState results
    

    【讨论】:

    • 我会试试的。在组件中进行 api 调用是不好的做法吗?我会注意的。
    • redux 的想法是移除那些对操作的“副作用”,因此您通常会将一个操作传递给组件并在 componentDidMount 中调用它——更多详细信息请参见github.com/gaearon/redux-thunk跨度>
    • 然而,直接在你的组件中调用 fetch 并不是一件可怕的事情或任何事情,实际上是完成任务的最有效和最快的方法。这增加了另一个抽象级别,这是程序员喜欢的,但不是必需的,除非您想非常“纯粹”并从组件中删除此类逻辑
    • 您是否需要对操作返回承诺?或者只是做类似 axios.get(pokemon.url);在函数内部?
    • 是的,如果您使用的是 redux-thunk,它希望您返回一个承诺(只是一个函数)。这个想法是你可以在那里调度多个动作,例如开始、成功和失败的动作 - 这样你就可以加载微调器并在失败时显示错误消息
    猜你喜欢
    • 1970-01-01
    • 2014-02-09
    • 2015-08-15
    • 2021-10-28
    • 2021-02-13
    • 2020-12-10
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多