为什么我不能把这个道具传递给子组件?

问题描述 投票:0回答:1

我在使用React Route时遇到了一个问题。我可以将pass2Parent={this.pass2Parent}传递给Search组件,但我不能将data={data}传递给Result组件。

我已经研究了几个小时的问题,我探索过在路由中使用render而不是组件。不幸的是,它的副作用是多次调用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,
  }
}
javascript reactjs react-router react-props
1个回答
1
投票

参数 data 传入 component={(data)=> 是一个SyntheticEvent,在它的作用域内覆盖了 data 值从状态。删去参数和它...


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

© www.soinside.com 2019 - 2024. All rights reserved.