我们正在使用API通过API获取CMS页面标题和其他详细信息。我们创建了菜单导航,如Home,About,We are。如何加载动态页面内容以及如何创建渲染?
class App extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
}
componentDidMount() {
axios.get('http://****.com/***/api/products/navigation_menu?app_id=27D8B4AD-170A-4B8E-9852-E48EC5EB42C8')
.then(res => {
this.setState({data: res.data.result_set});
});
}
_createMenuItems(){
return this.state.data.map((loaddata, index)=>
<li key={index}><Link to={loaddata.pro_cate_slug} >{loaddata.menu_custom_title}</Link></li>
);
}
render() {
return (
<div>
<ul>
{this._createMenuItems()}
</ul>
{this.props.children}
</div>
)
}
}
export default App;
答案 0 :(得分:0)
这是一个应该帮助您入门的基本示例。我基本上使用App
组件为所有路由进行渲染。一种更好的方法可能是动态创建页面的路由,然后使用特定页面的特定组件。
const { Router, Route, Link } = ReactRouter;
class App extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
}
componentDidMount() {
axios
.get(
"https://cdn.rawgit.com/fabe/6929b34fd6f30a13e85ddea480c7053d/raw/5fd6fbe535713c52fd2166e6d0f2d0de01381ff3/gistfile1.json"
)
.then(res => {
this.setState({ data: res.data.result_set });
});
}
_getSlug(slug) {
return slug.split('?')[0];
}
_createMenuItems() {
return this.state.data.map((loaddata, index) => (
<li key={index}>
<Link to={this._getSlug(loaddata.cmspage_slug)}>
{loaddata.cmspage_title}
</Link>
</li>
));
}
render() {
const { data } = this.state;
const { splat } = this.props.params;
let description = "";
// I'm setting the `description` to the corresponding one from the `data` state. `params.splat` is the slug from React Router.
data.map(page => {
let pageSlug = this._getSlug(page.cmspage_slug);
if (pageSlug == splat) {
description = page.cmspage_meta_description;
}
});
return (
<div>
<ul>
{this._createMenuItems()}
</ul>
<div>{description}</div>
</div>
);
}
}
// Use `App` for every route. Probably not the best way to solve this, but it gives you an idea.
ReactDOM.render(
(
<Router>
<Route path="*" component={App} />
</Router>
),
document.getElementById("View")
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://npmcdn.com/react-router@2.0.0/umd/ReactRouter.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.3/axios.min.js" charset="utf-8"></script>
<div id="View"></div>
&#13;