reactjs - 无法在 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)
}
请参阅图像我得到的这个对象
解决方案
让我们从头开始看你的例子:
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>;
};
要了解有关路由如何工作的更多信息,请阅读这篇文章。
推荐阅读
- node.js - 为什么节点快递在第一次请求后发送不同的标头
- react-apollo - 设置 ApolloGraphQL 持久化查询时,如何支持 /GraphQL?
- javascript - javascript Audio() 到底是什么,它是如何工作的?它与
- ruby - 哈希键和值
- python - 无法使用 docker compose 连接到 docker 容器上的 neo4j 数据库
- mysql - MySQL 8.0.21 中的 ROLLUP 问题
- javascript - 我的帖子请求以 https 形式获得响应,但不返回新页面(javascript)
- scala - 调用仅访问包含对象类型的静态方法
- java - 使用一个文件,将 60 个随机等级,数值介于 50 和 100 之间的值写入一个文件。读取文件,计数并显示为 A - f 级
- python - Python3 朋友的朋友