让我们从头开始看你的例子:
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 组件接受单个参数,因此 index 参数
现在指向这个对象,因此它会被记录。
解决这个问题的一个简单方法是用新函数替换 onClick 处理程序中的 YearMonth 组件,并从 YearMonth 中删除日志记录strong> 组件。
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>;
};
要详细了解路由的工作原理,请follow this article。