简体   繁体   中英

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

When I tried to pass a number as argument to function inside JSX the above error occured.

Working file Link: https://codesandbox.io/s/divine-hill-v3gl3?fontsize=14&hidenavigation=1&theme=dark&file=/new.js

React Component.


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;

You are using the prop object instead the actual data:

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

The problem you get is here:

function Rating(data) {

In a component you are receiving PROPS so you are getting an object like this:

data: {
 data: 1
}

In your code you are comparing with the object so you get the default case in the switch, returning the object above.

to fix it you can do:

function Rating({data}) {

or

function Rating(props) {

and use props.data for your comparations.

When you pass props to the component, you receive them as object. If you pass

<Rating data={data} />

then you receive props in a Rating component like { data: YOUR DATA }

Link to working sandbox https://codesandbox.io/s/fancy-smoke-wl8he

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM