寻求使用说明澄清效果

时间:2019-08-20 23:52:34

标签: reactjs use-effect

我已经在我创建的向导类型的React模式中成功实现了useEffectuseStatecreateContext。总而言之,这就是我所做的:

import React, { createContext, useState, useEffect } from 'react';
export const CustomerContext = createContext();
const CustomerContextProvider = (props) => {
  const [customer, setCustomer] = useState({
    // Define context structure and default values
  });

  useEffect(() => {
    // Perform async operations to get further default values 
    // from the DB
  };

  // Several functions (aka methods) of CustomerContext that are made
  // available to those React components that require them.  One of
  // them is `changeWizardIndex` which allows one to step forward or
  // backward in a series of Wizard pages (ex. Next / Back).
}

这是我对useEffect感到困惑的地方:在上述changeWizardIndex中,当“ Next button (renamed to "Complete" on that last Wizard page) is pressed then code within calls a separate function just below called completeWizard”时。确切地说,我是这样定义的:

const completeWizard = () => {
  // Within is the code to call an async POST request
  // Then there are calls to close the modal and to reset
  // the state of `CustomerContext` back to its default
}

我尝试在以下位置包装此函数:

useEffect(() => {
  // completeWizard function to go here
  }, []);

但是,当我这样做时,changeWizardIndex中的代码找不到completeWizard函数。当然,我从直觉上了解到useEffect包装器一定是问题所在(即它实际上将completeWizard置于“错误范围”内),但是应该如何解决?

需要明确的是,changeWizardIndex没有副作用,因此绝对不需要useEffect,但是completeWizard主要是关于副作用(即异步POST调用)的,所以绝对应该在useEffect包装器中。

最后,completeWizard还需要调用changeWizardIndex的其他两个同级函数,一个称为toggleModal,另一个称为resetState

因此,我正在寻求有关如何以正确的方式“跳入” useEffect包装程序的指南。

0 个答案:

没有答案