我已经阅读了Tyler Macginnis react-router的文档,但我很难找到解决问题的方法。
基本上我尝试用自定义页面(:page param)测试我的路由,但是console.log只打印"路径"功能
DynamicImport.js动态加载页面
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class DynamicImport extends Component {
state = {
component: null
};
async componentDidMount() {
const { path } = this.props;
const { default: Component } = await path().then((data) => {
return data;
});
this.setState({ component: <Component {...this.props} /> });
}
render() {
const { component } = this.state;
return <div>{component || <h1>Loading...</h1>}</div>;
}
}
DynamicImport.propTypes = {
path: PropTypes.func.isRequired
};
export const Top = () => (
<DynamicImport path={() => import('../../containers/Top')} />
);
export const News = () => (
<DynamicImport path={() => import('../../containers/News')} />
);
export const Show = () => (
<DynamicImport path={() => import('../../containers/Show')} />
);
export const Ask = () => (
<DynamicImport path={() => import('../../containers/Ask')} />
);
Routing.js to routing
import React from 'react';
import { NavLink } from 'react-router-dom';
import './Routing.css';
const Routing = () => (
<div className="navigation">
<ul className="navigation-nav">
<li>
<NavLink to="/" activeClassName="active">
Top
</NavLink>
</li>
<li>
<NavLink to="/news" activeClassName="active">
News
</NavLink>
</li>
<li>
<NavLink to="/show" activeClassName="active">
Show
</NavLink>
</li>
<li>
<NavLink to="/ask" activeClassName="active">
Ask
</NavLink>
</li>
</ul>
</div>
);
export default Routing;
App.js初始文件
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Routing from './containers/Routing/Routing';
import { Top, News, Show, Ask } from './containers/Routing/DynamicImport';
class App extends Component {
render() {
return (
<Router>
<div>
<Routing />
<div className="container">
<Route exact path="/" component={Top} />
<Route path="/top/:page" component={Top} />
<Route path="/news/:page" component={News} />
<Route path="/show/:page" component={Show} />
<Route path="/ask/:page" component={Ask} />
</div>
</div>
</Router>
);
}
}
export default App;
在网页中渲染首页并设置参数时,参数不存在...
import React, { Component } from 'react';
class Top extends Component {
constructor(props) {
super(props);
this.state = {
stories: []
};
}
componentWillMount() {
console.log(this.props);
}
render() {
console.log(this.props);
return <div />;
}
}
export default Top;
那个console.log打印这个......
出了什么问题?
答案 0 :(得分:0)
解决。我忘了将'道具'传递给......
export const Top = (props) => (
<DynamicImport path={() => import('../../containers/Top')} />
)