javascript - 为什么我不能将此道具传递给子组件?
问题描述
我一直遇到 React Route 的问题。我可以将 pass2Parent={this.pass2Parent} 传递给 Search 组件,但我不能将 data={data} 传递给 Result 组件。
我已经研究了几个小时的问题,并且探索了在路由中使用渲染而不是组件。不幸的是,它产生了多次调用 API 并耗尽我的津贴的副作用。
我只是不明白为什么它不能按原样工作..
render() {
let data = this.state;
console.log(data);
return (
<div style={{height: "inherit"}}>
<BrowserRouter>
<Switch>
<Route path='/' exact component={() => <Search pass2Parent={this.pass2Parent}/>}/>
<Route path='/result' exact component={(data) => <Result data={data}/>}/>
</Switch>
</BrowserRouter>
</div>
);
};
这是 console.log(data) 返回的内容:
{
images: {total: 8327, total_pages: 833, results: Array(10)},
weather: {coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 10000, …}
}
这是 console.log(this.props) 在子组件中的样子:
{
data: {
history: {length: 2, action: "POP", location: {…}, createHref: ƒ, push: ƒ, …},
location: { pathname: "/result", search: "", hash: "", state: undefined },
match: { path: "/result", url: "/result", isExact: true, params: {…} },
staticContext: undefined,
}
}
解决方案
data
传递给你的参数component={(data)=>
是一个 SyntheticEvent,它在它的范围内覆盖data
来自状态的值。删除论点,它...
<Route path='/result' exact component={() => <Result data={data}/>}/>
推荐阅读
- c# - 从 datalist 中的 imagebutton 获取 ID
- excel - .xlsm 文件不将区域列表分隔符视为管道,但默认采用逗号
- kubernetes - 在 GCP 中使用 Cloud Shell 访问私有 Kubernetes 集群
- android - 如何在 ReactJS android 应用程序中以编程方式截取屏幕截图?
- javascript - 在 Angular 网站上出现错误“无法读取未定义的属性”
- java - c3p0 池与其他应用程序一起执行
- debugging - IntelliJ IDEA 调试器可以自己设置断点吗?
- python - 未创建 Docker 容器
- javascript - 为每行记录生成按钮,将显示行的完整信息
- autohotkey - 返回一个全局变量,使用字符串作为变量名