Javascript 在ReactJS中将fetch返回的承诺作为上下文值传递
我试图将fetch请求响应从helper函数传递到ReactJS上下文 这是我的背景:Javascript 在ReactJS中将fetch返回的承诺作为上下文值传递,javascript,reactjs,Javascript,Reactjs,我试图将fetch请求响应从helper函数传递到ReactJS上下文 这是我的背景: const SomeContext = React.createContext(); const SomeProvider = SomeContext.Provider; const SomeConsumer = SomeContext.Consumer; export {SomeProvider, SomeConsumer}; 这是我的助手函数: function FetchU() { const
const SomeContext = React.createContext();
const SomeProvider = SomeContext.Provider;
const SomeConsumer = SomeContext.Consumer;
export {SomeProvider, SomeConsumer};
这是我的助手函数:
function FetchU() {
const zx = localStorage.getItem("zx");
const xx = localStorage.getItem("xx");
const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
accesstoken: accessToken,
userid: userid
}
};
if (userid !== null) {
fetch(
process.env.REACT_APP_API_URL + "/authenticated/get-roles",
requestOptions
)
.then(response => response.json())
.then(response => {
console.log(response);
});
} else {
console.log("not loggedin === no user permissions.");
}
}
export default FetchU;
这就是我如何利用我的上下文提供程序
<PermissionsProvider value="something">
<Child Component />
<SecondChild Component />
<ThirdChild Component />
</PermissionsProvider>
My helper函数是由应用程序内部的事件手动触发的,因此可以选择值=something
实际上可能等于null
或未定义
我想将FetchU
函数中的值替换为value=something
。有什么建议吗?对于您的案例,我将使用object作为默认值定义您的上下文
// Context default values.
const Context = React.createContext({
value: '',
loading: false,
updateContext: () => {},
});
然后在上下文的顶部创建一个提供者。提供者
const ContextProvider = ({ children }) => {
const [value, setValue] = React.useState('');
const [loading, setLoading] = React.useState(false);
const handleUpdateContext = useCallback(async () => {
// Call your api here
setLoading(true);
let newValue;
try {
newValue = await mockAPICall();
} catch (err) {
// handle err
} finally {
setLoading(false);
}
// Then update context value with your result.
setValue(newValue);
}, []);
const context = {
value,
loading,
updateContext: handleUpdateContext,
};
return (
<Context.Provider value={context}>
{/* I usually do this for extra flexibility */}
{typeof children === 'function' ? children(context) : children}
</Context.Provider>
);
}
const ContextProvider=({children})=>{
const[value,setValue]=React.useState(“”);
常量[loading,setLoading]=React.useState(false);
const handleUpdateContext=useCallback(异步()=>{
//在这里调用api
设置加载(真);
让新价值;
试一试{
newValue=wait mockAPICall();
}捕捉(错误){
//处理错误
}最后{
设置加载(假);
}
//然后用结果更新上下文值。
设置值(新值);
}, []);
常量上下文={
价值
加载,
updateContext:handleUpdateContext,
};
返回(
{/*我通常这样做是为了额外的灵活性*/}
{typeof children==='function'?子对象(上下文):子对象}
);
}
然后像这样在你的应用程序中使用它
const App = () => {
return (
<ContextProvider>
<div>
<Context.Consumer>
{({ value, loading }) => {
if (loading) return 'Loading...';
return (
<label>
Result in context :
<pre>
{JSON.stringify(value, '\t', '')}
</pre>
</label>
);
}}
</Context.Consumer>
<Context.Consumer>
{({ updateContext }) => (
<button onClick={updateContext}>Simulate API Call</button>
)}
</Context.Consumer>
</div>
</ContextProvider>
)
}
const-App=()=>{
返回(
{({value,loading})=>{
如果(加载)返回“加载…”;
返回(
上下文中的结果:
{JSON.stringify(值,'\t','')}
);
}}
{({updateContext})=>(
模拟API调用
)}
)
}
<> P>有一些事情要考虑,如果操作变得更复杂,也许你可以使用<代码> UrError Enter >代码>。您还可以添加error
状态,以防出现任何API错误
这是我为您准备的工作代码沙盒
希望有帮助