首页 > 解决方案 > 为什么我不能将此道具传递给子组件?

问题描述

我一直遇到 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,
  }
}

标签: javascriptreactjsreact-routerreact-props

解决方案


data传递给你的参数component={(data)=>是一个 SyntheticEvent,它在它的范围内覆盖data来自状态的值。删除论点,它...


<Route path='/result' exact component={() => <Result data={data}/>}/>


推荐阅读