【问题标题】:Button(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return nullButton(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null
【发布时间】:2021-06-30 17:47:53
【问题描述】:

我正在学习一个教程,并正在尝试编写一个程序,该程序在按下按钮时返回一个随机句子。我想出的是:

import React, { useState } from "react";

const Button = ({ onClick, text }) => {
  <button onClick={onClick}>{text}</button>;
};

const getRandomInt = (max) => {
  return Math.floor(Math.random() * max);
};

const App = () => {
  const anecdotes = [
    "If it hurts, do it more often",
    "Adding manpower to a late software project makes it later!",
    "The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.",
    "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
    "Premature optimization is the root of all evil.",
    "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
    "Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blod tests when dianosing patients",
  ];

  const [selected, setSelected] = useState(0);
  
  return (
    <>
      <Button
        onClick={()=>setSelected(getRandomInt(anecdotes.length()))}
        text="Press to get anecdote"
      />
      <div>{anecdotes[selected]}</div>;
    </>
  );
};

export default App;

当我似乎在运行“npm run”时,我的浏览器显示以下错误消息: '× 错误:按钮(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。'

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您在禁用自动返回的箭头函数语法中使用了大括号。要么做const Button = ({ onClick, text }) =&gt; &lt;button onClick={onClick}&gt;{text}&lt;/button&gt;;要么

    const Button = ({ onClick, text }) => {
      return <button onClick={onClick}>{text}</button>;
    };
    

    【讨论】:

      【解决方案2】:

      您的自定义 Button 组件不返回任何内容。你可能想这样做:

      const Button = ({ onClick, text }) => {
      return (<button onClick={onClick}>{text}</button>);
      };
      

      Arrow functions 如果没有大括号,则可以省略 return 语句。如果有,那么在这种情况下你将不得不写return;

      【讨论】:

        猜你喜欢
        • 2018-12-08
        • 2021-05-13
        • 2019-08-14
        • 1970-01-01
        • 2018-03-26
        • 2020-07-06
        • 2022-01-12
        • 2021-05-15
        • 2021-03-05
        相关资源
        最近更新 更多