簡體   English   中英

React,錯誤:對象作為 React 子項無效(找到:object 和鍵 {data})

[英]React , Error: Objects are not valid as a React child (found: object with keys {data})

當我嘗試將數字作為參數傳遞給 JSX 內的 function 時,發生了上述錯誤。

工作文件鏈接: 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;

您正在使用道具 object 代替實際數據:

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

你遇到的問題在這里:

function Rating(data) {

在您收到 PROPS 的組件中,您將獲得這樣的 object:

data: {
 data: 1
}

在您的代碼中,您正在與 object 進行比較,因此您在開關中獲得默認情況,返回上面的 object。

要修復它,您可以執行以下操作:

function Rating({data}) {

或者

function Rating(props) {

並使用 props.data 進行比較。

當你將 props 傳遞給組件時,你會收到 object。 如果你通過

<Rating data={data} />

然后你會在像 { data: YOUR DATA } 這樣的 Rating 組件中收到道具

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM