你将无法这样做:
您不能在反应的渲染阶段之外调用挂钩。
此外,即使您这样调用它,赋值也是局部的,不会影响上下文值。
要实现您想要的行为,您需要:
- 保存错误消息的状态以及状态设置器
- 每次错误更改时上下文值都应更改
- 您应该从调用您的钩子的组件中获取状态设置器
- 将您的状态设置器作为回调传递给您的异步函数
是这样的:
// context
export let ErrorContext = createContext({})
export let useErrorContext = () => useContext(ErrorContext)
// provider
let [errorMessage, setErrorMessage] = useState();
let value = useMemo(() => ({errorMessage, setErrorMessage}), [errorMessage])
<ErrorContext.Provider value={value}>
{children}
</ErrorContext.Provider>
// component
let {setErrorMessage} = useErrorContext();
export const myFunction = async (id, setErrorMessage) => {
setErrorMessage("SOME ERROR MESSAGE");
}
// later, in an event:
myFunction(id, setErrorMessage);
PS:此解决方案要求您为每个错误消息执行一个提供程序,以便您可以有多个,或者您应该更改抽象。
另一个解决方案看起来像是对我自己的库的提升,但事实并非如此,只是为了展示它解决这个问题的难易程度:
yarn add -D async-states react-async-states
import {useAsyncState, createSource} from "react-async-states"
// myErrorMessage should be unique, or else the library will warn
let myErrorMessageSource= createSource("myErrorMessage");
// in your component
let {state, setState} = useAsyncState(myErrorMessageSource);
// then use the state.data to display it
// in your async function, and your component would react to it
myErrorMessageSource.setState("SOME ERROR MESSAGE");
这只是该库的一个基本用例,请在选择它之前阅读the docs。