Javascript 警告:使用条件渲染的函数作为 React 子节点无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48371604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:05:24  来源:igfitidea点击:

Warning: Functions are not valid as a React child, using a conditional rendering

javascriptreactjs

提问by DamianFox


I'm trying to display the list of results taken from the response of wikipedia API. If the response doesn't show any list, it should show a different message. I am trying to do a conditional rendering.


我正在尝试显示从维基百科 API 响应中获取的结果列表。如果响应未显示任何列表,则应显示不同的消息。我正在尝试进行条件渲染。

Here is the code:

这是代码:

getData(e) {
        e.preventDefault();
        var search = e.target.search.value;
        var wikipediaEndPoint = "https://en.wikipedia.org/w/api.php?format=json&origin=*&action=query&generator=search&gsrnamespace=0&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch="+search;
        var wikipediaUrl = "https://en.wikipedia.org/?curid=";

        fetch(wikipediaEndPoint)
        .then(data => {
            return data.json();
        }).then(data => {
            var objectList = (data.hasOwnProperty("query")) ? data.query.pages : "";
            let resultList;

            if(objectList !== ""){
                resultList = Object.keys(objectList).map(function(key, index) {
                    return (
                        <div className="item" key={objectList[key].pageid}>
                            <a href={wikipediaUrl+objectList[key].pageid}>
                                <h1>{objectList[key].title}</h1>
                                <p>{objectList[key].extract}</p>
                            </a>
                        </div>
                    )
                });
            } else {
                resultList = (function() {
                    return (
                        <div className="item" key={1}>
                            <p>No results!</p>
                        </div>
                    )
                });
            }

            this.setState({search: resultList});
        })
    }

The result is shown here: <div className="items">{this.state.search}</div>

结果如下所示: <div className="items">{this.state.search}</div>

It works fine when the search field keyword finds some results, however, on the opposite case the console returns an error (or a warning):

当搜索字段关键字找到一些结果时,它工作正常,但是,在相反的情况下,控制台返回错误(或警告):

Warning: Functions are not valid as a React child. This may happen ifyou return a Component instead of <Component /> from render. Or maybeyou meant to call this function rather than return it.

Warning: Functions are not valid as a React child. This may happen ifyou return a Component instead of <Component /> from render. Or maybeyou meant to call this function rather than return it.

Where is the error? Am I doing the conditional rendering the right way?

错误在哪里?我是否以正确的方式进行条件渲染?

Thanks

谢谢

采纳答案by PhistucK

            resultList = (function() {
                return (
                    <div className="item" key={1}>
                        <p>No results!</p>
                    </div>
                )
            });

Why are you setting a function? Just set the <div...-

为什么要设置函数?只需设置<div...-

            resultList = (
                    <div className="item">
                        <p>No results!</p>
                    </div>
                )

Edit -

编辑 -

In order to really use a function (not sure why, though), the code would have to be a bit different -

为了真正使用一个函数(虽然不知道为什么),代码必须有点不同 -

            const Foo = (function() {
                return (
                    <div className="item" key={1}>
                        <p>No results!</p>
                    </div>
                )
            });
            resultList = (<Foo />)

Edit 2 -

编辑 2 -

The above edit works because React components do not have to be constructors/classes, they can also be a simple function that gets props as a parameter and returns JSX. I think this type of components is a bit limited, but it works.

上面的编辑是有效的,因为 React 组件不必是构造函数/类,它们也可以是一个简单的函数,将 props 作为参数并返回 JSX。我认为这种类型的组件有点有限,但它有效。

回答by Dan O

you're setting resultListto a function when objectList === "". either return a <div>directly, or else use that function as an IIFE:

你设置resultList时的功能objectList === ""。要么<div>直接返回 a ,要么将该函数用作IIFE

resultList = (function() {
  return (
    <div className="item" key={1}>
      <p>No results!</p>
    </div>
  )
})(); // note the parens here, which call the function