0

我的组件需要一个加载微调器。我正在使用反应钩子useEffect,因为我正在使用redux,所以我不能useState在这个组件中使用。

这是我到目前为止所得到的,它没有按预期工作。

import React, { useEffect } from 'react';
import { fetchData } from 'lib';


export default function Example(props) {

  let isFree = false;
  let isLoading = true;

  useEffect(() => {
    async function check() {
      const result = await fetchData(123);

      isLoading = false; // I am aware of react-hooks/exhaustive-deps
      if (!result){
        isFree = true; // I am aware of react-hooks/exhaustive-deps
      }
    }
    check();

    return function cleanup() {
      isLoading = false;
    };

  })

  const bookMe = ()=> {
    if (isLoading) {
      return false;
    }

    // do something
  };

  return (
    <div
      className="column has-text-centered is-loading">
      <div
        className={
          'button is-small is-outlined ' +
          ( isLoading ? ' is-loading' : '')
        }
        onClick={bookMe}
      >
        Select this slot
      </div>
    </div>
  );
}

注意:我试过useRef了,我没有得到答案。

注意:我可以使用类组件来实现解决方案,如下所示。跟随isLoading

但我的问题是重写整个事情有useEffect()没有 useState()

import React, { Component } from 'react';
import { fetchData } from 'lib';

export default class Example extends Component {
  _isMounted = false;

  state = {
    isFree: false,
    isLoading: true
  };

  componentDidMount() {
    this._isMounted = true;

    fetchData(123).then(result => {
      if (this._isMounted) {
        this.setState({ isLoading: false });
      }
      if (!result) {
        if (this._isMounted) {
          this.setState({ isFree: true });
        }
      }
    });
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  bookMe = () => {
    if (this.state.isLoading) {
      return false;
    }

    // do something
  };

  render() {
    return (
      <div
        className="column has-text-centered is-loading">
        <div
          className={
            'button is-small is-outlined ' +
            (this.state.isLoading ? ' is-loading' : '')
          }
          onClick={this.bookMe}
        >select this slot</div>
      </div>
    );
  }
}
4

1 回答 1

3

我正在使用 react hook useEffect 并且因为我使用的是 redux,所以我不能在这个组件中使用 useState。

实际上你可以使用 useState。

  • 状态管理是艰难的,需要做出决策。如果您使用 redux,则并非不能在组件中使用状态。
  • 问题是您想在哪里管理您的请求。如果您决定在组件中管理您的请求,则必须包含状态。

一般来说,Redux 更适合:

  • 存储应用程序各个部分所需的状态。
  • 复杂的状态管理。

let isFree = false; 
let isLoading = true;

在您的代码中,您没有使用 useState,但您实际上是在尝试使用状态。这是行不通的,因为每次 let 变量都会由函数新创建。

于 2019-08-08T18:06:46.687 回答