【问题标题】:Unable to handle state 'loading' properly in react with redux无法正确处理状态“加载”以与 redux 做出反应
【发布时间】:2020-07-16 14:56:20
【问题描述】:

嘿,伙计们刚刚搬到 redux,所以我正在做的反应是在 componentDidMount() 中,我正在调用 api,一旦我收到数据,我就将加载设置为 false(最初加载为 true)以摆脱'反应微调',

但是现在在 componentDidMount() 中使用 redux 之后,我正在调用另一个位于另一个中的操作创建器,并且我正在接收我的数据,那么我如何在这里管理“加载”?我可以以某种方式将动作创建器中的某些内容传递给我的组件以触发状态并将加载设置为 false 吗?或者还有其他的吗?大家是怎么管理的?

这是我的代码

Home.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));
  };
};

reducer 文件

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

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

};

export default getCategoryReducer;

【问题讨论】:

  • 我通常也会在我的 redux 存储中保持加载状态,所以当你完成加载时,你可以发送一个 LOADED 动作。另一种选择是在组件中添加loaded,这取决于allCategories 属性中是否包含任何内容。

标签: javascript reactjs redux react-redux redux-thunk


【解决方案1】:

您应该在reducer 文件中处理加载状态。目前,它在您的Component 文件中定义。例如,当您发送操作时,它也应该更新您的加载状态。我会在减速器中做这样的事情。

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 中阅读加载道具

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 2018-05-10
    • 1970-01-01
    • 2021-01-17
    • 2017-04-19
    • 2022-01-15
    • 2018-06-12
    • 2016-02-28
    相关资源
    最近更新 更多