我希望能够执行 ajax 调用,将 JSON 数组存储在名为“user”的变量中,并使其可用于我的应用程序中的所有无状态子组件。
我不确定在哪里放置 getJSON 调用。
JSON 文件:
{
"user": [{
"firstName": "Cliff",
"lastName": "Johnson",
"fullName": "Cliff Johnson",
"username": "cliffjohnson",
"userId": "8675309",
"email": "cliff@cliffjohnson.com",
"avatarSrc": "../images/avatar.png"
}]
}
入口点文件:
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, hashHistory } from 'react-router';
{/* import rest of pages Pages */}
window.React = React;
var user;
$.getJSON("./json/user.json", function(json){
user = json; // this is the object I want to make accessible to all children
});
render(
(<Router history={hashHistory} >
<Route path="/" component={App}>
<Route path="/frames" component={Frames} />
<Route path="/albums" component={Albums} />
<Route path="/channels" component={Channels} />
<Route path="/playlist" component={Playlist} />
<Route path="/mode" component={Mode} />
<Route path="/history" component={History} />
<Route path="/settings" component={Settings} />
</Route>
</Router>), document.getElementById('content')
);
应用文件:
import React from 'react';
import SideNav from './SideNav/SideNav';
import Frames from './Frames/Frames';
const App = ({ children }) => (
<div className="container">
<aside id="sidenav">
<SideNav />
</aside>
<main>
{children || <Frames />}
</main>
</div>
);
App.propTypes = {
children: React.PropTypes.object
};
export default App;
示例子组件:
import React from 'react';
const User = ({ avatarSrc, fullName }) => (
<div className="user">
<div className="avatar">
<img src={user.avatarSrc} alt="User Avatar" />
</div>
<div className="user-full-name">
{user.fullName}
</div>
</div>
);
export default User;