我已经在我创建的向导类型的React模式中成功实现了useEffect
,useState
和createContext
。总而言之,这就是我所做的:
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
包装程序的指南。