ReactJS Router 函数组件中如何带参数使用history.push方法?
问题原因&修复方案
你遇到的两个报错根源都是函数组件的参数使用错误,对应修复如下:
核心错误1:函数组件入参格式错误
React 函数组件的第一个入参永远是包含所有传入属性的props对象,不会自动拆分多个参数。你写的function Button(path, text)里,path实际拿到的是完整的props对象(而非你传入的路径字符串),text拿到的是组件的第二个预留参数ref(值为undefined)。
这就正好对应了你提到的线索:history.push要求传入string类型,你实际传入的是props对象(any类型)所以不生效;同时text为undefined渲染时就会抛出“no valid react child”错误。
核心错误2:调用组件时未传全必填属性
你调用<Button path="path/..."/>时只传了path属性,缺少必填的text属性,也会导致渲染报错。
完整修复代码
import {useHistory} from 'react-router-dom'; import { Component } from 'react'; // 可复用Button组件:直接从props中解构需要的属性 function Button({ path, text }) { const history = useHistory(); function handle(){ history.push(path); } return( <button onClick={handle}> {text} </button> ); } class Example extends Component{ render(){ return( <div> {/* 调用时传入所有必填属性,路径如需从根路由匹配请加/前缀 */} <Button path="/path/..." text="首页" /> {/* 可复用多次,传入不同属性即可 */} <Button path="/other/path" text="其他页面" /> </div> ); } } export default Example;
补充说明(适配react-router v6版本)
如果你使用的是react-router v6,useHistory已被弃用,替换为useNavigate即可,修改对应逻辑:
import { useNavigate } from 'react-router-dom'; function Button({ path, text }) { const navigate = useNavigate(); function handle(){ navigate(path); } return( <button onClick={handle}> {text} </button> ); }
内容的提问来源于stack exchange,提问作者Josué Cano
相关产品推荐
相关产品推荐

