簡體   English   中英

如何使用 redux 為反應 js 設置加載 state

[英]how to set a loading state for react js with redux

i'm using redux and i want to show an loading state for my app whenever my app is catching data from api and whenever i have an data of null in my reducers
我試過這個,但我沒有加載文本

    if (this.props.isSignedIn === true) {
      return <div
        style={{ textAlign: "right" }}>
        <Link to='/streams/new' className='ui button primary'>
          create new stream
      </Link>
      </div>
    }
    if (this.props.isSignedIn === false) {
      return <div style={{ fontSize: '30px' }}>Not a user? sign in now, it's free </div>
    }
    if (this.props.isSignedIn ===null) {
      <div>loading...</div>
    }
  }  

這是連接和mapstatetoprops function

const mapStateToProps = state => {
  return {
    streams: Object.values(state.streams),
    userId: state.auth.userId,
    isSignedIn: state.auth.isSignedIn
  };
};

export default connect(
  mapStateToProps,
  { fetchStreams }
)(StreamList);

這是減速機

import { SIGN_IN, SIGN_OUT } from '../actions/types';

const INTIAL_STATE = {
  isSignedIn: null,
  userId: null
};

export default (state = INTIAL_STATE, action) => {
  switch (action.type) {
    case SIGN_IN:
      return { ...state, isSignedIn: true, userId: action.payload };
    case SIGN_OUT:
      return { ...state, isSignedIn: false, userId: null };
    default:
      return state;
  }
};

這是動作

export const signIn = userId => {
  return {
    type: SIGN_IN,
    payload: userId
  };
};

export const signOut = () => {
  return {
    type: SIGN_OUT
  };
};

筆記:

除了 null

通常通過在商店設置“加載”屬性並添加額外的操作(例如“SIGN_INIT”)來完成

所以你的減速器看起來像這樣:


const INTIAL_STATE = {
  isSignedIn: null,
  loading: false,
  userId: null
};


export default (state = INTIAL_STATE, action) => {
  switch (action.type) {
    case SIGN_INIT:
      return { ...state, loading: true };
    case SIGN_IN:
      return { ...state, isSignedIn: true, loading: false, userId: action.payload };
    case SIGN_OUT:
      return { ...state, isSignedIn: false, loading: false, userId: null };
    default:
      return state;
  }
};

因此,當您嘗試登錄或注銷時,首先您發送 SIGN_INIT 將“加載”設置為 true。 每當請求完成時,SIGN_IN\SIGN_OUT 操作將在商店中更新您的“加載”道具,並且將通知組件加載完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM