【发布时间】:2020-05-16 02:44:14
【问题描述】:
在 react 项目中,有一个全局可用的警报和消息上下文。在任何给定的组件中,我都可以使用 context.setAlert() 来发送消息。
我将一些 API 获取逻辑提取到实用程序函数中。它不是一个组件。组件在渲染之前以各种方式导入和使用这个函数,有点像这样:
//MyComponent.js
import {fetchFromApi} from "../util"
import AlertContext from "../contexts/alert"
const MyComponent = () => {
const alertContext = useContext(AlertContext)
useEffect(() =>
fetchFromApi(...)
.then(() => alertContext.setAlert('All set'), [])
return <Something/>
}
所以在 fetchFromApi 中,我希望能够使用该 AlertContext.setAlert 方法。像这样的:
// util.js
export const fetchFromApi = (params) =>
fetch("...")
.then(something)
.then(somethingelse)
.then(response => {
// set alert from the AlertContext is what I want to access
if (response.status === 500) alertContext.setAlert('oh no')
return response
})
我不确定是否/如何更新组件外部的上下文状态。这可能吗?
【问题讨论】:
标签: reactjs react-context