首页 > 解决方案 > 无法在 React 中访问数组索引

问题描述

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

而且我真的不知道...

这是组件

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)
}

请参阅图像我得到的这个对象

在此处输入图像描述

标签: reactjsreact-routerreact-router-domreact-router-v4

解决方案


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

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组件。

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

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

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

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

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

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

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"];

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>;
};

要了解有关路由如何工作的更多信息,请阅读这篇文章


推荐阅读