更新ui组件时,prop更改了反应

发布于 2025-02-13 12:42:24 字数 1270 浏览 1 评论 0原文

我正在尝试使用React制作摩托车社交媒体。

当用户搜索摩托车型号时,它将显示所有规格以及拥有摩托车的人,以便用户可以与他们联系。

因此,我试图将所有所有者列表从一个页面传递给所有者lastlist.jsx作为道具,以便当所有者的数组准备就绪(从mongodb中获取后)时,onererSlist.jsx可以显示列表中的那些人。

我希望它显示“加载...”,当Prop Array为空时,一旦准备就绪,我就希望它重新渲染组件。

但是,即使在数组到达之后,该页面仍显示“加载..”,并且不会改变。

我在这里做错了什么?

另外,如果我知道我缺少这种错误的反应的基本概念,那就太好了。

所有者listlist.jsx

import React from "react";
import { useEffect, useState } from "react";

export default function OwnersList({ ownerObjectsArray }) {
  useEffect(() => {
    console.log(
      "ownerObjectsArray.length is like this ",
      ownerObjectsArray.length
    );
  }, [ownerObjectsArray]);
  if (ownerObjectsArray.length === 0) {
    console.log("yes, the array is empty. PLEASE WAIT");
    return <h2>Loading...</h2>;
  } else {
    console.log("ownerObjectsArray is not empty, so , i will set it as state.");
    return (
      <div>
        {ownerObjectsArray.map((ownerObject) => {
          return (
            <div key={ownerObject.username}>
              <h3>{ownerObject.username}</h3>
              <button>contact</button>
            </div>
          );
        })}
        OwnersList
      </div>
    );
  }
}

I am trying to make an motor cycle social media using React.

when user search for a motorCycle model, it will show all the specs, as well as people who own the motor cycle, so that an user can reach out to them.

So, I am trying to pass all the owners list from a page to OwnersList.jsx as props, so that when the array of owners are ready(after fetching from MongoDB), OwnersList.jsx can show those people on the list.

I want it to show "LOADING..." when the prop array is empty, and as soon as the prop array is ready, I want it to re-render components.

However, even after the array arrives, the page is still showing "LOADING.." and it does't change.

What am I doing wrong here?

Also, that would be great if I can know what kind of basic concepts of React I am missing to be stuck in this kind of bug.

OwnersList.jsx

import React from "react";
import { useEffect, useState } from "react";

export default function OwnersList({ ownerObjectsArray }) {
  useEffect(() => {
    console.log(
      "ownerObjectsArray.length is like this ",
      ownerObjectsArray.length
    );
  }, [ownerObjectsArray]);
  if (ownerObjectsArray.length === 0) {
    console.log("yes, the array is empty. PLEASE WAIT");
    return <h2>Loading...</h2>;
  } else {
    console.log("ownerObjectsArray is not empty, so , i will set it as state.");
    return (
      <div>
        {ownerObjectsArray.map((ownerObject) => {
          return (
            <div key={ownerObject.username}>
              <h3>{ownerObject.username}</h3>
              <button>contact</button>
            </div>
          );
        })}
        OwnersList
      </div>
    );
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你丑哭了我 2025-02-20 12:42:24

利用三元运算符(条件?结果:else)来有条件地渲染一个返回语句的jsx。

Props更改将触发重新渲染,因此它将再次评估landerObjectSarray.length.length,并确定要渲染的JSX。

不需要更多的代码:

import React from 'react'

export default function OwnersList({ ownerObjectsArray }) {
  return ownerObjectsArray.length ? (
    <div>
      {ownerObjectsArray.map((ownerObject) => (
        <div key={ownerObject.username}>
          <h3>{ownerObject.username}</h3>
          <button>contact</button>
        </div>
      ))}
      OwnersList
    </div>
  ) : (
    <h2>Loading...</h2>
  )
}

有一个带有“更改道具”的陷阱。如果对数组的引用不变,则不会触发重新渲染。因此,如果您只是在父组件中更新相同的引用,则孩子不知道该数组已更改。

例如:

const ownerObjectsArray = []
// do some stuff
ownerObjectsArray.push(newObject)

对变量的引用不会改变,仅在内存中的同一位置增加了一个。

但是,要创建对数组的新引用,请执行类似的操作:

let ownerObjectsArray = []
// do some stuff
ownerObjectsArray = [...ownerObjectsArray, newObject]

最好的是用usestate来控制数组,然后将状态传递给组件:

[ownerObjectsArray, setOwnerObjectsArray] = useState([])
// do some stuff
setOwnerObjectsArray((prev) => [...prev, newObject])

Make use of the ternary operator (condition ? result : else) to conditionally render JSX inside of one return statement.

Props changing will trigger a re-render so it will evaluate the ownerObjectsArray.length again, and determine which JSX to render.

Shouldn't need more code than this:

import React from 'react'

export default function OwnersList({ ownerObjectsArray }) {
  return ownerObjectsArray.length ? (
    <div>
      {ownerObjectsArray.map((ownerObject) => (
        <div key={ownerObject.username}>
          <h3>{ownerObject.username}</h3>
          <button>contact</button>
        </div>
      ))}
      OwnersList
    </div>
  ) : (
    <h2>Loading...</h2>
  )
}

There is one gotcha with "props changing". If the reference to the array doesn't change, then the re-render won't be triggered. So if you are just updating the same reference in the parent component, the child doesn't know that the array has changed.

Ex:

const ownerObjectsArray = []
// do some stuff
ownerObjectsArray.push(newObject)

The reference to the variable doesn't change, just one more addition to the same place in memory.

But, to create a new reference to the array, do something like this:

let ownerObjectsArray = []
// do some stuff
ownerObjectsArray = [...ownerObjectsArray, newObject]

Best yet, would be to control the array with useState and pass the state down to the component:

[ownerObjectsArray, setOwnerObjectsArray] = useState([])
// do some stuff
setOwnerObjectsArray((prev) => [...prev, newObject])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文