React - 将 JSON 对象传递给所有无状态子组件

IT技术 reactjs
2021-05-18 06:31:48

我希望能够执行 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;
1个回答

正如我在您的另一个问题中所解释的那样:您需要user在您的 中放置as 状态App,并setState()通过 props 将其传递到组件树中。

class App extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {};
  }
  componentDidMount() {
    $.getJSON("./json/user.json", (json) => {
      this.setState({user: json}); // Use setState to render the loaded data
    });
  }
  render() {
    return (
      <div className="container">
        <aside id="sidenav">
          <SideNav />
        </aside>
        <main>
          {/* Use cloneElement to add props to dynamic children */}
          {this.props.children ? React.cloneElement(this.props.children, {user: this.state.user}) : <Frames />}
        </main>
      </div>
    );
  }
}

这就是“没有 Flux 或 Redux”的 React 是如何完成的。如果您想在组件之外管理数据模型,那么您确实需要 Flux 或 Redux。

PS:我认为您想使用IndexRouteorIndexRedirect代替 render children || <Frames />