是否有办法让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} />
这就像我一样希望。
如果您需要我进一步解释,请告诉我 - 首先发布所有内容!
答案 0 :(得分:0)
您可以拥有一个constants.js
文件,您可以在其中导出要全局访问的任何变量,然后只需将这些变量导入到您需要的任何位置。
例如,在constants.js
:
export const name = "Colin";
然后在您的组件文件中,您可以执行import { name } from 'constants';
。
请注意,这是名为导出的示例。您可以查看this link以获取有关JavaScript导出的更多详细信息。
答案 1 :(得分:0)
在不使用父子关系的组件之间共享数据的最佳方法是使用Redux。使用redux的另一个原因是redux中的数据流与反应的数据流(作为道具)相称。
答案 2 :(得分:0)
是的,您可以全局使用这些获取的数据。有不同的方法可以使用它。
您可以将这些已提取的数据存储在localStorage
或sessionStorage
中。 localStorage
和sessionStorage
都构建在Web浏览器的应用程序中。您可以通过
localStorage
中
localStorage.setItem('key', JSON.stringify(data)
你可以
通过JSON.parse(localStorage.getItem('key'));
您可以使用firebase
应用程序存储数据并在需要的任何组件中使用它们。 Firebase是Google
提供的数据库服务,主要用作前端引擎的数据库,例如react
,angular
和vue
。
您可以将Redux与redux middleware
结合使用,例如redux-thunk
。 Redux
用于state management
。 Redux
使用store
来存储您的状态,并且可以在您需要的任何组件中访问它。其他州管理软件包是flux架构的Facebook和mobx。
您可以在youtube和电子学习门户网站上找到上述方法的教程。快乐的黑客攻击。