use*_*077 3 javascript reactjs react-router
我有一个PageBuilder组件,可以根据配置文件动态构建编辑/列表页面.我想要使用相同的PageBuilder组件的动态路由(如"/ collection/list","/ collection/edit/123123","/ dashboard"等).我无法让它工作 - 例如,如果我在/ collection/list中,当点击指向/ collection/edit/1231的链接时不起作用.只刷新该URL工作(反之亦然).我尝试将初始化代码设置为PageBuilder,componentWilLReceiveProps但它似乎每秒都调用它.我的路线看起来像这样:
<Route path="/" component={App}>
<IndexRedirect to="/dashboard" />
<Route path="/:page/:collection/:action(/:entity_id)" component={PageBuilder} />
<Route path="/:page" component={PageBuilder} />
</Route>
而我的PageBuilder:
constructor(props) {
super(props);
this.createSectionsHTML = this.createSectionsHTML.bind(this);
this.onChange = this.onChange.bind(this);
this.onSave = this.onSave.bind(this);
}
getPageName() {
return this.props.params.page.replace(/-/g, '_').toLowerCase();
}
componentWillReceiveProps(props) {
this.action = this.props.params.action;
}
componentWillMount() {
let pageName = this.getPageName();
this.props.dispatch(setInitialItem(pageName));
}
componentDidMount() {
let pageName = this.getPageName();
let { collection, entity_id } = this.props.params;
if (collection && entity_id) {
let { dispatch } = this.props;
dispatch(getCollectionEntity(collection, entity_id, pageName));
}
}
Run Code Online (Sandbox Code Playgroud)
有关每次重定向到不同路径时如何重新呈现页面的任何想法?如果我可以在重定向时卸载并重新安装组件会很棒,但我不知道如何告诉React Router这样做....
谢谢!
让this.state这样它就会控制你的组件如何被呈现.
现在,在内部componentWillReceiveProps,检查nextProps参数
componentWillReceiveProps(nextProps, nextState) {
if( <check in nextProps if my route has changed> ) {
let newState = Object.assign({}, this.state);
// make necessary changes to the nextState Object by calling
// functions which would change the rendering of the current page
this.setState({ nextState });
}
}
Run Code Online (Sandbox Code Playgroud)
这将componentWillReceiveProps仅在路线改变时采取行动.
现在在你的渲染功能中,
render() {
const { necessary, variables, to, render } = this.state;
let renderVariables = this.utilityFunctionsReqToRender(someArgs);
return (
<toRenderJsx>
...
</toRenderJsx>
)
}
Run Code Online (Sandbox Code Playgroud)
这将使您的组件在路由更改时"刷新".