then或catch方法内的usestate

pp

请需要您的帮助来解决内联错误

当我在then或catch方法中使用useBurgerState时,出现以下错误

ESLint:无法在回调内部调用React Hook“ useBurgerState”。必须在React函数组件或自定义的React Hook函数中调用React Hooks。(react-hooks / rules-of-hooks)

以下是整个功能:

const BurgerBuilder = props => {
  const [BurgerState, useBurgerState] = useState({
    Ingredients: {
      salad: 0,
      meat: 0,
      bacon: 0,
      cheese: 0
    },
    price: 0,
    purchased: false,
    Modal: false,
    spinner: false
  });

  const ContinueHandler = () => {
    // alert('Continue!!')
    const order = {
      ingredients: { ...BurgerState.Ingredients },
      price: BurgerState.price
    };
    useBurgerState({
      Ingredients: BurgerState.Ingredients,
      price: BurgerState.price,
      purchased: BurgerState.purchased,
      Modal: BurgerState.Modal,
      spinner: true
    });

    instance
      .post("/orders.json", order)
      .then(response => {
        useBurgerState({
          Ingredients: BurgerState.Ingredients,
          price: BurgerState.price,
          purchased: BurgerState.purchased,
          Modal: false,
          spinner: false
        });
      })
      .catch(error =>
        useBurgerState({
          Ingredients: BurgerState.Ingredients,
          price: BurgerState.price,
          purchased: BurgerState.purchased,
          Modal: false,
          spinner: false
        })
      );
  };
  const ZeroIngredients = { ...BurgerState.Ingredients };
  for (let index in ZeroIngredients) {
    ZeroIngredients[index] = ZeroIngredients[index] <= 0;
  }
  let ModalHtml = null;
  let SpinnerHtml = (
    <OrderSummary
      price={BurgerState.price.toFixed(2)}
      clicked_D={ModalHandler}
      clicked_S={ContinueHandler}
      Ingredients={BurgerState.Ingredients}
    />
  );

  if (BurgerState.spinner) {
    SpinnerHtml = <Spinner />;
  }
  if (BurgerState.Modal) {
    ModalHtml = (
      <Modal click={ModalHandler} show={BurgerState.Modal}>
        {SpinnerHtml}
      </Modal>
    );
  }
  return (
    <WithClass>
      <Burger Ingredients={BurgerState.Ingredients} />

      {ModalHtml}

      <BuildControls
        add={AddIngredientsHandler}
        remove={RemoveIngredientsHandler}
        disabled={ZeroIngredients}
        price={BurgerState.price}
        purchased={BurgerState.purchased}
        Modal={ModalHandler}
      />
    </WithClass>
  );
};

export default BurgerBuilder;
德鲁·里斯(Drew Reese)

这是因为您如何命名状态设置器useBurgerState

我必须以“ use”开头命名自定义挂钩吗?拜托 这个约定非常重要。没有它,我们将无法自动检查是否违反了Hooks规则,因为我们无法确定某个函数是否在其中包含对Hooks的调用。

使用自定义挂钩

我知道您不是在创建自定义钩子,但是您使用的命名约定另有说明,而linter正在标记它认为在嵌套函数中调用钩子的东西。

useState变量的标准约定与大多数变量命名约定(camelCase)相同。这里的例外是setter变量以set前缀开头

const [state, setState] = useState();
const [root, setRoot] = useState();
const [burgerState, setBurgerState] = useState();

这使您一眼就能分辨出什么是useState挂钩设置器。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章