javascript - 从数据库获取 HTML 到 React

标签 javascript html reactjs

我的测试 API 中有以下 JSON:

{
    "/page-one": "<div><h1 className='subpage'>Database page one!</h1><p className='subpage'>Showing possibility of page one</p><p className='subpage'>More text</p></div>",
    "/page-two": "<div><h1 className='subpage'>Database page two!</h1><p className='subpage'>Showing possibility of page two</p><p className='subpage'>More text</p></div>",
    "/page-two/hej": "<div><h1 className='subpage'>Database page two supbage hej!</h1><p className='subpage'>Showing possibility of page two with subpage</p><p className='subpage'>More text</p></div>"
}

我想创建一个动态页面,使用 URL 路径名来确定应使用/显示哪个 HTML。我尝试过以下方法:

import React from 'react';

import Utils from "../../utils";
import './not-found-controller.css';

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

        this.getPage = this.getPage.bind(this);
    }

    async getPage() {
        const pageList = await Utils.http.get('http://demo5369936.mockable.io/pages');
        console.log(pageList.data);
        const possiblePages = Object.keys(pageList.data);

        if (possiblePages.indexOf(window.location.pathname) !== -1) {
            return pageList.data[window.location.pathname];
        } else {
            return (
                <div>
                    <h1 className="subpage">404 - Page not fpund!</h1>
                    <p className="subpage">The page you are looking for is not found. Please contact support if you thing this is wrong!</p>
                </div>
            );
        }
    }

    render() {
        return (
            <section className="not-found-controller">
                { this.getPage }
            </section>
        );
    }
}

export default GenericController;

但这不起作用。我只收到以下错误:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
    in section (at not-found-controller.js:31)
    in NotFoundController (at app.js:166)
    in Route (at app.js:164)
    in Switch (at app.js:88)
    in div (at app.js:87)
    in App (created by Route)
    in Route (created by withRouter(App))
    in withRouter(App) (at src/index.js:18)
    in Router (created by BrowserRouter)
    in BrowserRouter (at src/index.js:17)

API 调用正确,console.log(pageList.data); 正确打印 JSON。我尝试搜索如何包含这样的 HTML,但没有找到任何让我理解的答案。

最佳答案

这里有 3 个错误,但是你的浏览器控制台应该已经告诉你这些错误了。

首先,您的 getPage 方法是异步,但 React 渲染过程应该是同步的,并立即执行存在的任何数据。如果数据不存在,组件仍应渲染(您可以从渲染返回 null 来渲染“无”)。相反,请在渲染 channel 之外获取数据,并在数据可用时调用 setState

其次,getPage 返回一个 HTML 字符串,该字符串不会以这种方式进行解析,而是按原样呈现。您需要使用 dangerouslySetInnerHTML Prop 。

第三,如jitesh指出,您缺少函数调用括号。

考虑到所有因素,您需要类似以下的内容(只需快速将其组合在一起,但您应该明白想法):

constructor(props, context) {
    super(props, context);
    this.state = {
        pageData: undefined
    };
}

componentDidMount() {
    this.getPage();
}

async getPage() {
    const pageList = await Utils.http.get('http://demo5369936.mockable.io/pages');

    this.setState({
        pageData: pageList.data[window.location.pathname]
    });
}

render() {
    if (this.state.pageData) {
        return (
            <section
                className="not-found-controller"
                dangerouslySetInnerHTML={{ __html: this.state.pageData }}
            />
        );
    } else {
        // Not found or still loading...
    }
}

关于javascript - 从数据库获取 HTML 到 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54288776/

相关文章:

javascript - JQuery 弹跳是不是跳错了地方?

javascript - 默认情况下,Node.js session 是如何处理的?

javascript - 浏览器中的自动增量验证短信代码(otp || 2fa)

javascript - 通过 React js 从具有属性的项目列表中获取随机项目

javascript - 类型错误 : undefined is not an object 'createElement' of undefined - React Native

html - 浏览器正在覆盖我代码中的所有元素并将它们变成链接

javascript - 如何使用JavaScript和offsetWidth来排列表格?

javascript - 如何使用React来setState并避免递归?

javascript - 如何过滤嵌套数组中的字符串?

javascript - 使用 watch.js 取消监视对象时出现问题