在 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
})
我不确定是否/如何更新组件外部的上下文状态。这可能吗?
最佳答案
修改fetchFromApi 的代码,让它接受一个带有回调函数的附加参数配置。您可以相应地调用回调。
希望这对您有所帮助。
关于reactjs - 是否可以在 react 组件之外更新上下文状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61831233/