React Router Dom中如何正确向Layout传递回调与状态?报错白屏求助
React Router Dom 状态与回调传递错误修复
问题分析
你的代码出现白屏和报错,核心问题集中在这几点:
- 函数组件(Layout、Header)错误使用
this.props,函数组件的props是通过参数传入,不能用this访问 - Menu组件中
onSearchF依赖this.state.data,但state里未初始化data字段,会触发Cannot read properties of undefined (reading 'filter')错误 - Menu组件传递
onSearch时,没有传递keyword参数,导致回调无法接收搜索关键词 - Menu组件同时用箭头函数定义
onSearchF和constructor里的bind,属于冗余操作(箭头函数自动绑定this,无需手动bind)
修正后的完整代码
1. Menu 类组件
class Menu extends Component { state = { searchBlock: false, data: [] // 初始化data字段,避免filter调用报错 }; // 箭头函数自动绑定this,无需constructor内手动bind onSearchF = (keyword) => { const filtered = this.state.data.filter((entry) => Object.values(entry).some( (val) => typeof val === "string" && val.toLowerCase().includes(keyword.toLowerCase()) ) ); // 可添加逻辑:比如将筛选结果存入state // this.setState({ filteredData: filtered }); }; render() { return ( <div className="content"> <Routes> {/* 直接传递函数引用,无需匿名函数包裹 */} <Route path="/" element={<Layout searchBlock={this.state.searchBlock} onSearch={this.onSearchF}/>} > <Route index element={<Home data={this.state.data} num={this.state.data.length} />} /> </Route> </Routes> </div> ); } } export default Menu;
2. Layout 函数组件
// 函数组件通过参数接收props const Layout = (props) => { return ( <> <Header sblock={props.searchBlock} onS={props.onSearch}/> </> ); }; export default Layout;
3. Header 函数组件
// 函数组件通过参数接收props function Header(props) { // 示例:模拟输入关键词后调用父组件传递的回调 const handleSearch = () => { props.onS("测试关键词"); console.log(props.sblock); }; return ( <header className="header"> <button onClick={handleSearch}>搜索</button> </header> ); } export default Header;
关键修正总结
- 函数组件必须通过参数接收props,禁止使用
this.props - 类组件中用箭头函数定义的方法,无需手动在constructor里bind this
- 确保state中所有用到的字段提前初始化,避免undefined相关报错
- 传递回调函数时,优先直接传递函数引用;若需额外传参,在子组件内处理参数传递逻辑
内容的提问来源于stack exchange,提问作者wch
相关产品推荐
相关产品推荐

