9阅网

您现在的位置是:首页 > 知识 > 正文

知识

reactjs - React动态路由+CMS

admin2022-10-29知识18

我正在针对我的CMS构建一个React应用,它提供了一个用于获取页面等的API。然而,我有关于如何使用React Router进行动态路由的问题。我不知道任何URLs,因为页面是在我的CMS中定义的,并且可以在用户创建、命名和删除页面时随时更改。

到目前为止,我已经创建了一个通配符路由。

<Route path="*" component={PageResolver} />

指向了一个组件,这个组件解析了要服务的页面组件。因此,当我点击frontpage''或说'品牌'时,该路由将通过我的PageResolver调用我的CMS输出的API。然后,CMS会响应创建什么类型的pagecomponents。为此,我创建了一个小的页面对象。

const pages = {
    'frontpage': FrontPage,
    'standardpage': StandardPage,
    'filterpage': FilterPage
};

如果我点击frontpage,CMS就会回复 "frontpage "的页面类型,这样我就知道要通过我的PageResolver渲染什么组件了。

我的PageResolver是这样的。

class PageResolver extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            page: null
        };
    }

    componentDidMount() {
        this.getPage(this.props);
    }

    componentWillReceiveProps(nextProps) {
        this.getPage(nextProps);
    }

    private getPage(props) {
        const { url } = props.match;

        axios({
            method: 'GET',
            url: 'http://localhost:3000/pages',
            params: {
                url
            }
        }).then(({ data }) => {
            this.setState({ page: null });

            if (data[0]) {
                const pageType = data[0].type;

                this.setState(() => ({ page: pages[pageType] }));
            } else {
                this.setState(() => ({ page: NotFound }));
            }
        });
    }

    render() {
        const { page: PageComponent } = this.state;

        return (
            PageComponent ? (
                <PageComponent />
            ) : null
        );
    }
}

有没有什么正式的方法或者至少是更好的方法来实现这个功能呢?上面的代码看起来有点黑?