使获取数据全局可访问 - 做出反应

时间:2018-04-17 09:49:23

标签: reactjs

是否有办法让fetch引入的数据全局可供React中的其他组件使用?

目前,我有一个名为page.json的json文件,其数据如下所示:

{
"logo": {
    "src": "images/logo.png"
},
"logout": {
    "text": "Logout"
},
"comingSoon": {
    "title": "There's more to come!",
    "text": "We know it might look a bit bare here right now, but don't worry - we're working on lots of new features coming soon...",
    "points": [
        {
            "id": 1,
            "title": "View documents plus saved quotes and exclusive discounts",
            "text": "You can do all this right now"
        },
        {
            "id": 2,
            "title": "Make simple changes",
            "text": "Change your email address, phone number or marketing permissions - Coming August 2018"
        },
        {
            "id": 3,
            "title": "Make all changes",
            "text": "Add a car, tell us you've moved house, the posibilities are endless - Coming April 2025"
        }
    ]
},
"test": "hello"

}

我希望我的组件能够访问此数据,目前使用fetch()调用此数据:

        class FetchDemo extends React.Component {
        constructor(props) {
            super(props);

            this.state = {
              pageData: []
            };
        }

        componentDidMount() {
            fetch('./page.json').then(res => res.json())
            .then( (result) => {
                this.setState({ 
                    pageData: result
                });
            });
        }

        render(){
            return ( 
                <span>
                {this.state.pageData}
                </span>
            )
        }
    }

我创建了一个带有内联数组的const,所以我可以像这样调用它们 <WelcomeMessage name={policies[0].id} /> 这就像我一样希望。

如果您需要我进一步解释,请告诉我 - 首先发布所有内容!

3 个答案:

答案 0 :(得分:0)

您可以拥有一个constants.js文件,您可以在其中导出要全局访问的任何变量,然后只需将这些变量导入到您需要的任何位置。

例如,在constants.js

export const name = "Colin";

然后在您的组件文件中,您可以执行import { name } from 'constants';

请注意,这是名为导出的示例。您可以查看this link以获取有关JavaScript导出的更多详细信息。

答案 1 :(得分:0)

在不使用父子关系的组件之间共享数据的最佳方法是使用Redux。使用redux的另一个原因是redux中的数据流与反应的数据流(作为道具)相称。

答案 2 :(得分:0)

是的,您可以全局使用这些获取的数据。有不同的方法可以使用它。

  1. 您可以将这些已提取的数据存储在localStoragesessionStorage中。 localStoragesessionStorage都构建在Web浏览器的应用程序中。您可以通过

    将值存储在localStorage

    localStorage.setItem('key', JSON.stringify(data)你可以 通过JSON.parse(localStorage.getItem('key'));

  2. 从localStorage中检索数据
  3. 您可以使用firebase应用程序存储数据并在需要的任何组件中使用它们。 FirebaseGoogle提供的数据库服务,主要用作前端引擎的数据库,例如reactangularvue

    < / LI>
  4. 您可以将Reduxredux middleware结合使用,例如redux-thunkRedux用于state managementRedux使用store来存储您的状态,并且可以在您需要的任何组件中访问它。其他州管理软件包是flux架构的Facebook和mobx

  5. 您可以在youtube和电子学习门户网站上找到上述方法的教程。快乐的黑客攻击。