【问题标题】:Laravel 7 + React render error: Nothing was returned from renderLaravel 7 + React 渲染错误:渲染没有返回任何内容
【发布时间】:2020-11-27 18:11:11
【问题描述】:

我在 Laravel 7 应用程序中有简单的反应组件。如果我尝试编写渲染方法,它会给我一个错误:渲染没有返回任何内容。如果我只使用 return() 而没有渲染它可以工作。我做错了什么?

import React from 'react';
import ReactDOM from 'react-dom';

function ItemsList() {

    /*constructor(props)
    {
        //super(props);
        //this.state.list = [1,2,3,4,5,6,7,8,9];
    }*/

    let state = {
        list: [1, 2, 3, 4, 5, 6, 7, 8, 9],
        test: 'this is state.test value'
    }

    function render() {

        const list = state.list.map(item => {
            <li>{item}</li>
        })

        return (
            <div onClick={handleClick}>This is Items List component and {state.test}</div>
        )
    }


    function handleClick(e) {
        alert("beeeeeeeeeeeeeeeeeee");
    }
}

export default ItemsList;

if (document.getElementById('itemsList')) {
    ReactDOM.render(<ItemsList />, document.getElementById('itemsList'));
}

【问题讨论】:

  • 您不需要渲染函数,因为您使用的是功能组件。所以只需将 return 语句移出渲染函数并删除渲染函数定义。
  • 我编辑了这个问题。现在,如果我想创建带有项目列表的 const 列表,则会出现错误:
  • 我认为你需要学习 React 基础知识。官方教程是一个很好的开始。 reactjs.org/docs/hello-world.html
  • 这就是我现在正在做的事情。

标签: reactjs laravel-7


【解决方案1】:

render 函数用于基于类的组件中,因为您使用的是函数式组件,所以您不需要 render 方法,只需 return 来渲染您的 JSX。

function ItemsList() {

    /*constructor(props)
    {
        //super(props);
        //this.state.list = [1,2,3,4,5,6,7,8,9];
    }*/

    let state = {
        list: [1, 2, 3, 4, 5, 6, 7, 8, 9],
        test: 'this is state.test value'
    }

        const list = state.list.map(item => {
            // Here this is JSX element so you must return it.
            return (<li>{item}</li>)
        })

return (
            <div onClick={handleClick}>This is Items List component and {state.test}</div>
<ul>{list}</ul>
        )



    function handleClick(e) {
        alert("beeeeeeeeeeeeeeeeeee");
    }
}

【讨论】:

  • 好的,我明白了。但是如何才能将 ul 值返回给 jsx?
  • @Čamo 查看我的更新答案。在 map 函数中使用 return 来返回 JSX 元素
  • 哦,很抱歉不必要的编辑。你比我快@Zayn :)
  • @mafirat 没问题:D
猜你喜欢
  • 2020-09-14
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 2018-04-05
  • 2020-09-02
  • 1970-01-01
  • 2020-07-24
  • 2021-01-01
相关资源
最近更新 更多