简体   繁体   English

如何从 react/redux 中的加载操作触发加载 animation

[英]How to trigger loading animation from a loading action in react/redux

I am developing my first react/redux web app that fetches concerts from an external api.我正在开发我的第一个 react/redux web 应用程序,该应用程序从外部 api 获取音乐会。 I have several actions in my action creator regarding this including, "LOADING_CONCERTS", "GET_CONCERTS", AND "SET_CONCERTS" .我的动作创建者对此有几个动作,包括"LOADING_CONCERTS", "GET_CONCERTS", AND "SET_CONCERTS" I then render these concerts in a concert list component.然后我将这些音乐会呈现在一个音乐会列表组件中。 Is it possible to add a loading bar component to render while redux is on the loading action?是否可以在 redux 正在进行加载操作时添加加载栏组件进行渲染? Some code:一些代码:

my async axios:我的异步 axios:

export const getConcerts = (artist) => {
      return (dispatch) => {
        dispatch({ type: 'LOADING_CONCERTS' });
        return axios.get(${api_url})
          .then(concerts => {
            dispatch({ type: 'GET_CONCERTS', concerts })
            dispatch({ type: 'SET_CONCERTS', concerts })
            dispatch(addReviewsToConcerts(concerts))
          })
          .catch( err=> {
            console.log(err.code)
            console.log(err.message)
            console.log(err.stack)
          }
          )
        }
    }

my reducer:我的减速机:

const initialState = []

export default (state = initialState, action) => {
  switch (action.type) {
    case 'LOADING_CONCERTS':
      return state;
    case 'GET_CONCERTS':
      return action.concerts.data
    case 'ADD_REVIEWS_TO_CONCERTS':
      return action.concerts
    case 'SAVE_CONCERT':
      return action
    default:
      return state;
  }
}

the concerts container:音乐会容器:


import React from 'react';
import ConcertSearchFormWrapper from './ConcertSearchFormWrapper';
import ConcertsList from '../.././components/concerts/ConcertsList';
import { connect } from 'react-redux';

const Concerts = (props) => {
    return (
      <div className="concerts-container">
        <ConcertSearchFormWrapper />
        { (props.concerts.length > 0 && props.concerts !== '\n{warn=Not found}\n') ? <ConcertsList /> : null}
      </div>
    )
};

export default connect((state) => ({ concerts: state.concerts })) (Concerts);

and then the list component:然后是列表组件:

import React from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
import { withRouter } from 'react-router-dom'
import { saveConcert } from '../.././actions/concerts/concerts'




const ConcertsList = ({concerts, saveConcert}) => {

    const date = (datetime) => {
      return new Date(datetime).toDateString()
    }

    return (

      <div className = "concerts-list">

        {concerts.sort((a, b) => (a.datetime < b.datetime) ? 1 : -1).map(c => <><Link key={c.id} to={`/concerts/${c.id}`}  onClick={()=>saveConcert(c)}>{c.lineup[0]} at {c.venue.name} on {date(c.datetime)}</Link><br/></>)}
      </div> 
    )
}



const mapStateToProps = (state, ownProps) => {
  return {

      concerts: state.concerts
  }
}

export default withRouter(connect(mapStateToProps, {saveConcert})(ConcertsList))

Here is how to add a loading spinner or a loading bar这是添加加载微调器或加载栏的方法

  1. update your innitial state to include a loding indicator ( for example 'isLoading' boolean.更新您的初始 state 以包含一个 loding 指示器(例如“isLoading”boolean。

const initialState = { isLoading: false, concerts: [], reviews: [] };

  1. Change your case statments to properly update the state on each action, below is roughly how I do it更改您的案例陈述以正确更新每个操作的 state,以下是我的大致方法
const concertReducer = (state = initialState, action) => {
  switch (action.type) {
    case "LOADING_CONCERTS":
      return { ...state, isLoading: true };
    case "GET_CONCERTS":
      return { ...state,
               concerts: action.payload,
               isLoading: false };
    case "ADD_REVIEWS_TO_CONCERTS":
      return { ...state,
              reviews: action.payload };

    default:
      return state;
  }
};

export default concertReducer;
  1. bring in the isLoading prop to your component using connect and mapStateToProps使用 connect 和 mapStateToProps 将 isLoading 属性引入组件
  2. use ternary operator to check if 'isLoading' is true and conditionally render your spinner or loading bar as follows使用三元运算符检查“isLoading”是否为真,并有条件地渲染您的微调器或加载条,如下所示
 {props.isLoading ? (
                <YourLoadinBarHere' />
              ) : (
                <Component or something to render when isLoading is false/>
              )}

Now, your loading bar will be displayed while the data is fetching ( props.isLoading == true ) of course there are other solutions like using HOC pattern but this is how I usually do it.现在,在获取数据时将显示您的加载栏( props.isLoading == true )当然还有其他解决方案,例如使用 HOC 模式,但这是我通常的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM