reactjs 使用Params获取URL ID并通过react中的索引查找项目

px9o7tmv  于 2023-06-05  发布在  React
关注(0)|答案(2)|浏览(69)

我已经使用参数来获取我之前链接到它的页面的URL,并且在这个阶段还可以,但是我不能相应地设置项目。

const {id} = useParams();
const [item, setItem] = useState([]);

useEffect(() => {
  fetch("https://.../V1/homepage/consts_list_homepage")
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      const selectedItem = data.data.find((item,index) => index + 1 === id);
      setItem(selectedItem);
    })
    .catch((error) => console.log(error));
}, []);

我应该提到的是,因为我的items数据中没有id,所以我使用了index+1而不是id。它呈现了id,但我想知道为什么项目不设置。我收到加载中...对于<h2 className="drname"> {item ?${item.Fname} ${item.Lname}: "Loading..."} </h2>,我已经将路由路径更改为“..../:id”,如果您帮助我解决问题,我将非常感谢

lx0bsm1f

lx0bsm1f1#

我会在这里做几件事:
1 -检查“id”是否真的包含它应该包含的内容
2 -为什么要在item中保存数组而不是元素?我希望有一个项目,所以你需要改变几件事:

// Item is initialized as null
const [item, setItem] = useState(null);
...
// The find method will return an array with only 1 item, so that take the first element of the array as selectedItem
const [selectedItem] = data.data.find((item,index) => index + 1 === id);
bt1cpqcv

bt1cpqcv2#

在stackoverflow中提问的奇迹,用它strugging了2个小时就解决了。只要改变它:const selectedItem = data.data[id - 1];

相关问题