簡體   English   中英

無法正確處理 state“加載”與 redux 反應

[英]Unable to handle state 'loading' properly in react with redux

嘿,伙計們剛剛搬到 redux,所以我正在做的反應是在 componentDidMount() 中,我打電話給 api,一旦我收到數據,我就將加載設置為 false(最初加載為 true)以擺脫“反應微調器” ',

但是現在在 componentDidMount() 中使用 redux 之后,我正在調用另一個在另一個中的操作創建器,並且我正在接收我的數據,那么我如何在這里管理“加載”? 我可以以某種方式將動作創建器中的某些內容傳遞給我的組件,以觸發 state 並將加載設置為 false? 或者還有其他方法嗎? 大家都是怎么管理的?

這是我的代碼

主頁.js

class home extends Component {
  UNSAFE_componentWillMount() {
    this.props.verifyToken();
  }

  componentDidMount() {
    this.props.categoryAction();

  }
  constructor(props) {
    super(props);
    this.state = {
      categoriesWithTheirImages: [],
      displayToggle: false,
      loading: false,
    };
  }


  renderCategory = () => {

    return this.props.allCategories.map((item) => {
      return (
        <div
          className="category_div"
          key={item._id}
          onClick={() => this.setState({ displayToggle: true })}
        >
          <img
            src={item.image}
            alt="miss-mistake"
            className="category_image_home"
          />
          <span className="category_heading_home">{item.categoryName}</span>
        </div>
      );
    });

  };

  render() {

    if (this.state.loading) {
      return (
        <div className="sweet-loading-main">
          <FadeLoader
            css={override}
            sizeUnit={"px"}
            size={50}
            color={"#ff9d72"}
            loading={this.state.loading}
          />
        </div>
      );
    } else {
      console.log(this.props.allCategories);
      return (
        <React.Fragment>
          {/* <Fade left> */}
          <Header />
          <div className="main_content_homepage">
            <p className="category_select">Please select a category</p>
            <div className="category_list">{this.renderCategory()}</div>
          </div>
          {this.renderStoryActionDialog()}
          {/* </Fade> */}
        </React.Fragment>
      );
    }
  }
}


const mapStateToProps = (state) => {
  console.log(state);
  const images = [family, ring, beer, feedback, academic];
  let categoriesWithImages = state.getCategoryReducer.map((item, index) => {
    item.image = images[index];
    return item;
  });
  console.log(categoriesWithImages);
  return { allCategories: categoriesWithImages };
};
export default connect(mapStateToProps, { verifyToken, categoryAction })(home);

和我的 action.js 文件

import { CATEGORY } from "../actionTypes";
export const categoryAction = ()=> {
  return dispatch => {
    fetch("http://localhost:3000/api/get_categories", {
      method: "GET",
    }).then(res=>res.json())
      .then(response => {
          console.log(response)
        dispatch({ type: CATEGORY, payload: response });
      })
      .catch(err => console.log("Eror in adding", err));
  };
};

減速器文件

import { USER, CATEGORY} from "../actionTypes";
const getCategoryReducer = (state = [], action) => {

  switch (action.type) {
    case CATEGORY:
      return action.payload;
    default:
      return state;
  }

};

export default getCategoryReducer;

您應該在reducer文件中處理加載 state。 目前,它在您的Component文件中定義。 例如,當您調度操作時,它也應該更新您的加載 state。 我會在減速器中做這樣的事情。

import { USER, FETCH_CATEGORY, FETCH_CATEGORY_SUCCESS, FETCH_CATEGORY_FAIL} from "../actionTypes";
const INITIAL_STATE = {
    loading: false,
    err: false,
    data: []
}
const getCategoryReducer = (state = INITIAL_STATE, action) => {

  switch (action.type) {
    case FETCH_CATEGORY:
       return Object.assign({}, state, {
            loading: true,
            data: [],
        })

      case FETCH_CATEGORY_SUCCESS
          return Object.assign({}, state, {
            loading: false,
            data: action.payload,
        })

       case FETCH_CATEGORY_FAIL
          return Object.assign({}, state, {
            loading: false,
            data: action.payload,
            err: true
        })

    default:
      return state;
  }

};

export default getCategoryReducer;

你的動作文件看起來像這樣

import { FETCH_CATEGORY, FETCH_CATEGORY_SUCCESS, FETCH_CATEGORY_FAIL } from "../actionTypes";
export const categoryAction = ()=> {
  //setting loading to true
  return dispatch => {
    dispatch({ type: FETCH_CATEGORY });
    fetch("http://localhost:3000/api/get_categories", {
      method: "GET",
    }).then(res=>res.json())
      .then(response => {
         //setting loading to false
        dispatch({ type: FETCH_CATEGORY_SUCCESS, payload: response });
      })
      .catch(err => console.log("Eror in adding", err);  dispatch({ type: FETCH_CATEGORY_FAIL, payload: err }););
  };
};

然后,您可以在Home.js中閱讀加載道具

暫無
暫無

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

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