除非我刷新,否则不会显示来自深层嵌套子组件的道具

时间:2017-09-26 15:04:50

标签: reactjs redux react-router-v4

我正在构建一个反应应用程序,我使用Redux来管理状态并对路由器v4做出反应以进行路由。我使用webpack作为模块捆绑器。它有这种结构。

-Wrapper
 -Home /
 -Homepage /h
    --GalleryContainer  /h/gallery
       ---Gallery  /h/gallery
       ---Item    /h/gallery/:itemId
    --About /h/about
    --Links /h/links

我在Item组件,我只会渲染匹配itemId的元素。当我第一次点击显示时,它不会渲染,除非我刷新,在某些情况下渲染模块的错误找不到(对于图片)但渲染,如果我刷新页面。渲染在其他组件上工作正常,但不能在这个上显示适当的道具需要匹配的参数。

任何有关正确方向的输入或帮助都将受到赞赏。

import React from 'react'

 class Item extends React.Component {

  render() {

   const item=this.props.items[this.props.match.params.itemId]

    return (
      <div>
      <h1> {item.title} </h1>
      </div>

    )
  }
}

export default Item

修改:从连接组件传递的道具通常显示在Item组件中,就像点击后显示console.log(this.props.items)一样。但是一旦他们受到自定义参数const item=this.props.items[this.props.match.params.itemId]的限制,我就会遇到这个问题。

添加GalleryContainer路线

<div>
    <Route path={`${this.props.match.path}`} 
    exact render={(props)=><Gallery 
        gallery={this.props.gallery}  
        {...props}  />} />

    <Route path={`${this.props.match.path}/:itemId`} 
    render={(props)=><Item 
        gallery={this.props.gallery}
        item={this.props.items} {...props} />} />

</div>

如果要发布其他组件以澄清此问题,请与我们联系。

解决方案 它终于奏效了。事实证明我在

中添加了一个空格
<Link to={`h/portfolio/${pod.code}`}>

解释了第一次渲染时的错误。

1 个答案:

答案 0 :(得分:1)

试试这个。

        import React from 'react'

        class Item extends React.Component {
            constructor(props){
                super(props);
                this.state={item:null};
            } 

            componentWillMount() 
            {
                this.setState({item:this.props.items[this.props.match.params.itemId]});
            }

            componentWillReceiveProps(nextProps) {
                this.setState({item:nextProps.items[nextProps.match.params.itemId]});
            }

        render() {
            let {item} = this.state;
            return (
            <div>
            <h1> item?item.title:""} </h1>
            </div>

            )
        }
        }

        export default Item