【问题标题】:React , Error: Objects are not valid as a React child (found: object with keys {data})React,错误:对象作为 React 子项无效(找到:带有键 {data} 的对象)
【发布时间】:2020-11-03 14:33:41
【问题描述】:

当我尝试将数字作为参数传递给 JSX 内部的函数时,发生了上述错误。

工作文件链接:https://codesandbox.io/s/divine-hill-v3gl3?fontsize=14&hidenavigation=1&theme=dark&file=/new.js

反应组件。


function Rating(data) {
  // This function indent to display number 0 to 3 based on 'data'; 
  switch (data) {
    case data <= 0: {
      return <div>0</div>;
    }
    case 0 < data <= 1: {
      return <div>1</div>;
    }
    case 1 < data <= 2: {
      return <div>2</div>;
    }
    case 2 < data <= 3: {
      return <div>3</div>;
    }
    default:
      return data;
  }
}

function some() {
  return (
    <div>
      <Rating data={product.totalrating} />
    </div>
  );
}

export default some;

【问题讨论】:

  • 您提供的示例有效。这个问题可以标记为已解决吗?
  • 谢谢,可以给我代码吗?

标签: javascript reactjs


【解决方案1】:

您使用的是 prop 对象而不是实际数据:

// not Rating(data), 
// as the argument of function component is a prop object
function Rating({data}) {
  //...
  return data;
}

【讨论】:

【解决方案2】:

你遇到的问题在这里:

function Rating(data) {

在您收到 PROPS 的组件中,您将获得这样的对象:

data: {
 data: 1
}

在您的代码中,您正在与对象进行比较,因此您在开关中获得默认情况,返回上面的对象。

要修复它,您可以这样做:

function Rating({data}) {

function Rating(props) {

并使用 props.data 进行比较。

【讨论】:

    【解决方案3】:

    当您将 props 传递给组件时,您会收到它们作为对象。 如果你通过了

    <Rating data={data} />
    

    然后您会在评级组件中收到道具,例如 { data: YOUR DATA }

    链接到工作沙箱https://codesandbox.io/s/fancy-smoke-wl8he

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 2021-05-19
      • 2018-01-12
      • 2020-02-27
      • 2021-05-19
      • 2021-03-16
      • 2021-06-20
      • 1970-01-01
      相关资源
      最近更新 更多