微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法访问 React 中的数组索引

如何解决无法访问 React 中的数组索引

这个组件正在映射一个数组,我在另一个函数中通过 onClick 传递数组的索引,在控制台之后我得到了对象。

我真的不知道...

这里是组件

const MonthName = () => {
 return <>
   {month.map((nameOfMonth,index) => 
    <div key={index}  onClick={() =>CurrentMonthDates(index)}>
    <Link to="/yearMonth" >
    <div> 
      <h3>{nameOfMonth}</h3>
      </div>
      </Link>
    </div>)}
    </>

在这里我传递索引

const CurrentMonthDates = (index) => {
 console.log(index)
}

查看我得到的这个对象的图像

enter image description here

解决方法

让我们从头开始看你的例子:

import { Link,BrowserRouter,Route } from "react-router-dom";
export default function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <MonthName />
        <Route path="/yearMonth" component={YearMonth} />
      </BrowserRouter>
    </div>
  );
}

let month = ["Jan","Feb","March"];

const MonthName = () => {
  return (
    <>
      {month.map((nameOfMonth,index) => (
        <div key={index} onClick={() => YearMonth(index)}>
          <Link to="/yearMonth">
            <div>
              <h3>{nameOfMonth}</h3>
            </div>
          </Link>
        </div>
      ))}
    </>
  );
};

const YearMonth = (index) => {
  return <div>{console.log(index)}</div>;
};

我们的目标是创建一个应用程序,将月份名称列表显示为超链接(MonthName 组件),点击这些链接中的任何一个,我们应该导航到 YearMonth 组件。

现在,当点击一个月的链接时会发生什么。生成了两个事件,一个 routing 事件和一个在 div 中注册的 onClick 事件。并且这两个事件都被传递给功能组件YearMonth

因此,当 onClick 事件执行时,它会将当前索引传递给功能组件,因此它会被记录。

现在,当路由事件被触发时,语句

<Route path="/yearMonth" component={YearMonth} />

被执行,并且组件 YearMonth 被渲染。但是在使用 react-routing 机制时,Route 组件总是将路由对象作为函数参数传递给它们呈现的组件。在这种情况下,YearMonth 组件。由于 YearMonth 组件接受单个参数,因此索引参数 现在指向此对象,因此它会被记录。

解决此问题的一个简单方法是使用新函数替换 onClick 处理程序中的 YearMonth 组件,并从 YearMonth 中删除日志记录强> 组件。

import { Link,"March"];

function yearMonth(index){
  console.log(index);
}

const MonthName = () => {
  return (
    <>
      {month.map((nameOfMonth,index) => (
        <div key={index} onClick={() => yearMonth(index)}>
          <Link to="/yearMonth">
            <div>
              <h3>{nameOfMonth}</h3>
            </div>
          </Link>
        </div>
      ))}
    </>
  );
};

const YearMonth = () => {
  return <div>Hi</div>;
};

要详细了解路由的工作原理,请follow this article

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。