【问题标题】:Route not rendering component when Url changesUrl更改时路由不呈现组件
【发布时间】:2016-12-26 09:12:20
【问题描述】:

我有以下 ProductThumbnail 组件,当我单击链接时,它会更新 URL 并更改路由以重定向到 ProductDesc 组件。它会正确生成 URL /productDescRedux/itemId。

const ProductThumbnail = (props) => {
 const itemId = props.product
 return(
  <div>
    <Link to={`/productDescRedux/${itemId.id}`}>
     <div>
      <h1>{props.product.headline}</h1>
      <img src={props.product.images[0].imagesUrls.entry[1].url} alt="Thumbnail small pic"/>
      <p></p>
     </div>
   </Link>
  </div>
 )
}

ProductThumbnail.propTypes = {
 product: React.PropTypes.object
};

export default ProductThumbnail;

尽管 URL 发生了变化,它并没有调用组件 ProductDesc,我必须重新加载页面才能显示组件 ProductDesc。下面的路线和组件 ProductDesc

const Routes = function(){
 return(
  <Provider store={store}>
   <Router history={ hashHistory }>
    <Route path="/" component={ Container }>
     <IndexRoute component={ Home } />
     <Route path="/productredux" component={ App } >
      <IndexRoute component={ ProductsGrid }/>
      <Route path="/productDescRedux/:id" component={ ProductDesc } />
     </Route>
    <Route path="*" component={ NotFound } />
   </Route>
  </Router>
 </Provider>
 )
}

export default Routes;

const ProductDesc = ()=>({
 render(){
  return (
   <div>
    <h1>hello</h1>
    <p>Yeah</p>
   </div>
  )
 }
})

在这里完成使用 connect() 的 App 组件以及 Main 组件

function mapStateToProps(state){
  return {
    products:state.products
  }
}

function mapDispatchToProps(dispatch){
  return bindActionCreators(actionCreators,dispatch);
}

const App = connect(mapStateToProps,mapDispatchToProps)(Main);

export default App;

//在不同的文件中

const Main = (props) => ({
    render(){
      return (
        <div>
          {React.cloneElement(props.children, this.props)}
        </div>
      )
    }
})

export default Main;

所以我不明白为什么在更改 URL 时,路由没有调用组件 ProductDesc。有什么见解吗?

【问题讨论】:

  • ProductThumbnail 在路由层次结构中声明的位置在哪里?是ProductsGrid 的孩子吗?
  • 是的,我小时候在 ProductsGrid 中调用它
  • 你能把App的组件代码也包括进来吗?或在 gist 或 jsbin 中提供您的代码。它将帮助其他人更好地了解您的问题

标签: reactjs redux react-router


【解决方案1】:

主要组件的语法问题,它是所有组件的父组件。我需要

{React.cloneElement(this.props.children, this.props)} 

而不是

{React.cloneElement(props.children, this.props)}

Ref issue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-06
    • 2021-12-05
    • 2018-02-21
    • 2021-04-02
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多