如何用api的数据初始化状态

问题描述 投票:1回答:1

我正在创建一个从api(pokeapi.co)获取数据的React / Redux应用程序。我使用axios获取数据。当我在反应组件上显示数据时,会导致数据为undefined的错误。经过一番挖掘后,我发现我的状态首先返回初始状态,即空对象,然后返回api数据。但它没有显示出反应。我是React的新手所以我猜它与axios异步功能有关。如何使用api的初始数据设置状态或等待呈现数据直到状态有api的数据?

这是减速机

function pokemonReducer(state={}, action) {
    switch (action.type) {
        case pokemonsActions.GET_POKEMON_SUCCESS:
            {
                return  {...state, data: action.payload.data}
            }

        default:
            {
                return state;
            }
    }
}

export default pokemonReducer

这是行动

export const GET_POKEMON_SUCCESS = 'GET_POKEMON_SUCCESS'
export const GET_POKEMON_ERROR = 'GET_POKEMON_ERROR'

function getPokemonSuccess(response) {
    return {
        type: GET_POKEMON_SUCCESS,
        payload: response
    }

}

function getPokemonError(err) {
    return {
        type: GET_POKEMON_ERROR,
        payload: err
    }
}
export function getPokemon() {
    return (disp,getState) => 
             {
                return pokeAPI.getPokeAPI()
                              .then((response) => { disp(getPokemonSuccess(response))})
                              .catch((err)=> disp(getPokemonError(err)))

             }
}

商店

const loggerMiddleware = createLogger()
const middleWare= applyMiddleware(thunkMiddleware,loggerMiddleware);

const store = createStore(rootReducer,preloadedState,
 compose(middleWare, typeof window === 'object' && typeof window.devToolsExtension !== 'undefined'
  ? window.devToolsExtension() : (f) => f
))


const preloadedState=store.dispatch(pokemonActions.getPokemon())

export default store

在React组件中

function mapStateToProps(state) {
  return {
    pokemons:state.pokemons
  }
}

    class PokemonAbility extends React.Component {

        render(){
            return (
                <div>
                <div className="header">
                  <h1>Fetch Poke Api with axios</h1>
                 </div>
                    <main>
                    <h3> Display pokemons abilities </h3>
                        <p>{this.props.pokemons.data.count}</p>
                    </main>
                </div>
                )
        }
    }


    export default connect(
      mapStateToProps
    )(PokemonAbility)

Api数据示例

{
    "count": 292,
    "previous": null,
    "results": [
        {
            "url": "https://pokeapi.co/api/v2/ability/1/",
            "name": "stench"
        },
        {
            "url": "https://pokeapi.co/api/v2/ability/2/",
            "name": "drizzle"
        },
        {
            "url": "https://pokeapi.co/api/v2/ability/3/",
            "name": "speed-boost"
        }
    ],
    "next": "https://pokeapi.co/api/v2/ability/?limit=20&offset=20"
}
reactjs api redux axios
1个回答
3
投票

您在加载数据之前渲染组件。有很多策略可以解决这个问题。没有特别的顺序,这里有一些例子:

1. Short circuit the render

如果数据不存在,您可以通过返回加载消息来短路渲染:

function mapStateToProps(state) {
    return {
        pokemons:state.pokemons
    }
}
class PokemonAbility extends React.Component {
    render(){
        if (!this.props.pokemons.data) {
            return (
                <div>Loading...</div>
            );
        }
        return (
            <div>
                <div className="header">
                    <h1>Fetch Poke Api with axios</h1>
                </div>
                <main>
                    <h3> Display pokemons abilities </h3>
                    <p>{this.props.pokemons.data.count}</p>
                </main>
            </div>
        );
    }
}

export default connect(mapStateToProps)(PokemonAbility);

2. Lift the data check to a parent component

您可以将mapStateToProps移动到更高的组件,或抽象出视图组件,并仅在数据准备好时呈现视图:

function mapStateToProps(state) {
    return {
        pokemons:state.pokemons
    }
}
class SomeHigherComponent extends React.Component {
    render(){
        return (
            this.props.pokemons.data ?
                <PokemonAbility pokemons={this.props.pokemons} /> :
                <div>Loading...</div>
        );
    }
}

3. Higher order component data checking

您可以将组件包装在“更高阶组件”(一个接受组件类并返回组件类的函数)中,以在渲染之前检查该prop是否存在:

function EnsurePokemon(ChildComponent) {
    return class PokemonEnsureWrapper extends React.Component {
        render() {
            return (
                this.props.pokemons.data ?
                    <ChildComponent {...this.props} /> :
                    <div>Loading...</div>
            );
        }
    }
}

用法:

export default connect(
    mapStateToProps
)(EnsurePokemon(PokemonAbility))

并且您可以在此EnsurePokemon HOC中包装任何子组件,以确保在数据加载之前它不会呈现。

© www.soinside.com 2019 - 2024. All rights reserved.