javascript - 将上下文与 api 调用一起用于根级组件

标签 javascript reactjs

我是 React 上下文的新手,但我认为 redux 的工作原理是这样的,但没有找到正确的方法。

所以我有一个组件,一旦我获得数据,我将从 api 获取数据,一旦数据加载组件,我需要显示加载器

但是我如何将值设置为上下文并使用它。

看下面的片段

class App extends Component{

    componentDidMount(){
        this._fetchData()
    }

    _fetchData = async () => {
        const response = await fetch("http://www.example.com", {method: "GET"})
        const data = await response.json()
        // how can i use context and set the value
    }

    // how should i use a provider to the router so basically i need to get the data every where in the route
    render(){
        return(
            <Router>
            { Object.keys(context.data).length > 0 ?
                <Layout>
                    <Switch>
                        <Route path="/sample" exact component={SampleHomePage} />
                        <Route path="/sample/profile" component={SampleProfile} />
                        <Route path="/sample/about" component={SampleAbout}/>
                    </Switch>
                </Layout>
                : <p>Data Loading </p>}
            </Router>
        )
    }
}


// profile.js

import React from  'react';

const profile = () => {
  //how to get the contex value here
}

export default profile

最佳答案

看看这个 codesandbox 并检查我是如何处理上下文的。

https://codesandbox.io/s/2p0koqr81p

关键是您需要一个额外的组件作为上下文。 在这种情况下,我只是将提取调用中的数据保存到上下文中。

因此,您必须向上下文提供更新的数据,然后您才能在任何您想要的组件中使用它。

我同意@Joru 的观点,在您的用例中使用上下文可能是不必要的,但我正在尝试回答这个问题。

关于javascript - 将上下文与 api 调用一起用于根级组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55147539/

相关文章:

google-maps - react 谷歌地图没有出现

javascript - Angular - ng-repeat 不适用于搜索 Controller

javascript - Mongoose 的日期错误

javascript - 检测加载 iframe 内容失败

reactjs - 如何在 Gatsby 站点的 iframe 中渲染带有 Emotion 样式的 React 组件?

reactjs - 为什么我的 React 应用程序在 webpack-dev-server 编译后显示空白页面?

javascript - React + Redux,render() 没有返回任何内容

javascript - 在回调中设置 Prop 值

javascript - 动态添加的类由于某种原因无法被引用

javascript - 有没有一种方法可以在不进行任何渲染的情况下计算字符串高度?