[英]Is it possible to update a context state outside of a react component?
在 React 項目中,警報和消息有一個全局可用的上下文。 在任何給定的組件中,我都可以使用 context.setAlert() 來發布消息。
我有一些 API 提取邏輯提取到實用程序 function 中。它不是組件。 組件在渲染之前以各種方式導入和使用這個 function,有點像這樣:
//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
})
我不確定是否/如何更新組件外部的上下文 state。 這可能嗎?
修改 fetchFromApi 的代碼,使其接受一個附加參數配置,回調為 function。您可以相應地調用回調。
希望這有幫助。
您可以改變 object 並在上下文提供程序中設置 setAlert 屬性。 這個object可以被fetchApi使用。 我假設 fetchApi 僅從 Alert 上下文中的組件調用,因此當 fetchApi 在 object 中使用 setAlert 時,它保證被設置:
const passSetAlert = { setAlert: (x) => x }; const AlertContext = React.createContext();// mutate passSetAlert function AlertProvider(props) { const [alert, setAlert] = React.useState('AA'); passSetAlert.setAlert = setAlert; return ( <AlertContext.Provider value={{ alert, setAlert }}> {props.children} </AlertContext.Provider> ); } const fetchFromApi = (message) => setTimeout(() => { passSetAlert.setAlert(message); }, 2000); function App() { const [count, setCount] = React.useState(0); const alertContext = React.useContext(AlertContext); const click = () => { const newCount = count + 1; setCount(newCount); fetchFromApi(newCount); }; return ( <div> <button onClick={click}>change alert</button> Alert is: {alertContext.alert} </div> ); } ReactDOM.render( <AlertProvider> <App /> </AlertProvider>, document.getElementById('root') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.