React userParams in Const

问题描述 投票:0回答:1

我成功地从URL获得了参数。我想将其传递给const值,如下所示。

let { id } = useParams(); //Got the param value
const currentpage = data.page1; //Instead of page1 I want to pass {id} as below

const currentpage = data.{ id }; //This is not working.

我的实际代码:

function Child() {
// We can use the `useParams` hook here to access
// the dynamic pieces of the URL.
let { id } = useParams();
const currentpage = data.page1;
return (
<div>
  <h3>ID: {id}</h3>

            <div className="container">
            {                   
                currentpage.map((rows, i) => { 
                    return (
                   //Will return page here
javascript reactjs react-native
1个回答
0
投票

首先:更改json数据以更好地反映页面数组

customData.json:

{
  "pname": "Project Name",
  "pages": [
    { "name": "Home", "content": "xyz" },
    { "name": "About Us", "content": "abc" }
  ]
}

然后,如果您在页面的URL中使用/ 0/1/2等id,则代码可能是:

import data from './customData.json';
function Child() {
  // We can use the `useParams` hook here to access
  // the dynamic pieces of the URL.
  let { id } = useParams();

  // this is not needed anymore
  //const currentpage = data.page1;

  // the parseInt is because the id will be a string and needs to be converted to an int
  const { name, content } = data.pages[parseInt(id)];

  return (
    <div>
      <h3>ID: {id}</h3>

      <div className="container">
        {name}
        {content}
      </div>
    </div>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.