简体   繁体   English

对象作为 React 子对象无效 - 请改用数组

[英]Objects are not valid as a React child - use array instead

So I realize that objects can't be rendered, but I am having a hard time figuring out how to fix this error after trying to add a loading spinner when fetching data.因此,我意识到无法渲染对象,但是在尝试在获取数据时添加加载微调器后,我很难弄清楚如何解决此错误。 Once I added the ternary operator, the data no longer passed to my child component and gave me the error code above.一旦我添加了三元运算符,数据就不再传递给我的子组件并给了我上面的错误代码。 Any help would be appreciated.任何帮助,将不胜感激。

const Dashboard = () => {
  const [isLoading, setLoading] = useState(false);
  const [marsData, setMarsData] = useState([]);

  const getMarsData = useCallback(async () => {
    try {
      setLoading(true);

      const res = await fetch('/api/nasa/mars');

      if (res.ok) {
        const jsosData = await res.json();
        setMarsData(jsosData.photos.slice(1, 6));
      } else {
        throw new Error(res.statusText);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => console.log(marsData), [marsData]);

  useEffect(() => {
    getMarsData();
  }, [getMarsData]);

 return (
    <div>
      {isLoading ? (
        marsData
      ) : (
        <Col s={4}>
          <Preloader active color="blue" flashing={false} size="big" />
        </Col>
      )}
      <MarsRoverPhotos data={marsData} />

      <MarsWeather />
    </div>
  );
};

And here is my MarsRoverPhotos component这是我的 MarsRoverPhotos 组件

const MarsRoverPhotos = ({data}) => {
  return (
    <div>
      <Slider
        fullscreen={false}
        options={{
          duration: 500,
          height: 400,
          indicators: true,
          interval: 6000,
        }}
      >
        {data.map((d) => (
          <Slide image={<img key={d.id} alt="" src={d.img_src} />}>
            <Caption
              placement="right"
              style={{height: '30px', paddingTop: '175px'}}
            >
              <h3>{d.camera.name}</h3>
              <h5 className="light grey-text text-lighten-3">
                {d.camera.full_name}
              </h5>
            </Caption>
          </Slide>
        ))}
      </Slider>
    </div>
  );
};

The error it's telling exactly what to do:它确切地告诉了要做什么的错误:

Can't see what you are doing with this component:看不到你在用这个组件做什么:

<MarsRoverPhotos data={marsData} />

But you are passing the response from jsosData.photos.slice(1, 6) which its an object not an array, so React is complaining that you are trying to render object, but React don't know what to do with it.但是你传递了来自jsosData.photos.slice(1, 6)的响应,它是一个 object 而不是一个数组,所以 React 抱怨你正在尝试渲染 object,但 React 不知道如何处理它。

Probably inside of <MarsRoverPhotos data={marsData} /> you have something like:可能在<MarsRoverPhotos data={marsData} />你有类似的东西:

return (<div>{marsData}</div>) // <-- that its rendering an object

The solution:解决方案:

You should check what are your receiving on jsosData.photos.slice(1, 6) most likely you are a receiving something like:您应该检查您在jsosData.photos.slice(1, 6)上收到的内容,很可能您收到的内容如下:

{
  "someId1": { value: "imgSrc" },
  "someId2": { value: "imgSrc"}
}

So what you need to do its iterate over the object the easy and standard way its:因此,您需要以简单且标准的方式对 object 进行迭代:

function MarsRoverPhotos(props) {
   const {data} = props;

    return Object.keys(data).map(key => <div>{data[key].value}</div>)
}

And you should be able to render your component.你应该能够渲染你的组件。 cheers!干杯!

Not sure if it's the most efficient way, but I did seem to solve it via a more basic approach to conditional rendering.不确定这是否是最有效的方法,但我似乎确实通过更基本的条件渲染方法解决了它。

if (isLoading) {
    return (
      <div>
        <Col s={4}>
          <Preloader active color="blue" flashing={false} size="big" />
        </Col>
      </div>
    );
  } else {
    return (
      <div>
        <MarsRoverPhotos data={marsData} />
      </div>
    );
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 对象作为 React-Child 无效 &gt; 使用数组代替异常 - Objects are not valid as React-Child > use an array instead exception 对象作为 React 子级无效,渲染一组子级,使用数组代替 - Objects are not valid as a React child, render a collection of children, use an array instead React错误:对象作为React子对象无效,如果要渲染子代集合,请改用数组 - React Error: Objects are not valid as a React child,If you meant to render a collection of children, use an array instead react matrerial ui Error: Objects are not valid as a React child 如果您打算渲染一组子项,请改用数组 - react matrerial ui Error: Objects are not valid as a React child If you meant to render a collection of children, use an array instead 对象作为 React 子级无效。 如果您打算渲染一组子项,请改用数组 - 错误 Solidity - React - Objects are not valid as a React child. If you meant to render a collection of children, use an array instead - Error Solidity - React “对象作为 React 子对象是无效的。 如果您打算渲染一组子项,请改用数组。” 错误 - “Objects are not valid as a React child. If you meant to render a collection of children, use an array instead.” error 如何修复错误:对象作为 React 子对象无效。 如果您打算渲染一组孩子,请改用数组 - How to fix error: Objects are not valid as a React child. If you meant to render a collection of children, use an array instead 对象作为 React 子级无效(找到:object 和键 {value})。 如果您打算渲染一组孩子,请改用数组 - Objects are not valid as a React child (found: object with keys {value}). If you meant to render a collection of children, use an array instead 对象作为 React 子级无效(找到:object 和键 {weight})。 如果您打算渲染一组孩子,请改用数组 - Objects are not valid as a React child (found: object with keys {weight}). If you meant to render a collection of children, use an array instead 对象作为 React 子级无效如果您要渲染子级集合,请改用数组 - Objects are not valid as a React child If you meant to render a collection of children, use an array instead
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM