无法使用React Router Link组件访问状态值

时间:2018-05-30 17:19:23

标签: javascript reactjs react-router

我正在尝试将海报图像从组件A传递到组件B.我搜索了许多不同的示例,但没有任何效果。我正在使用react-router v4和Link来执行此操作。我使用Cloudinary React API设置我的组件A如下,以加载拇指图像。

class Topics extends Component {
 state = {
  topics: [
   {id: 1, text:'Learning', thumb:'Learning', poster: '../static/street.jpg'}, 
   {id: 2, text:'Healthy Living', thumb:'Healthy', poster: '../static/healthy-crop.jpg'}, 
   {id: 3, text: 'Mentorship', thumb:'Mentor'}, 
   {id: 4, text: 'Community', thumb: 'Neighbour'}, 
   {id: 5, text: 'Economic Dev', thumb: 'open'}, 
   {id: 6, text: 'Urban Parks', thumb:'Park'}
  ]
 };

 render() {
  const { topics } = this.state;
  return (
   <section>
    <CloudinaryContext cloudName='dxanqdr7i'>
      <PageTitle>Topics</PageTitle>
      <h2>Choose a topic from below to learn more</h2>
      <div>
        {topics.map((topic, index) => (
          <div key={index}>                
            <Link 
              key={topics.id} 
              to={{
                pathname: `/${topic.text}`,
                state: {
                  poster: topic.poster
                }
              }}>
              {topic.text}
            </Link>
            <Image key={topic}  publicId={topic.thumb} 
              dpr="auto"
              responsive
              width='auto'
              crop="scale">
            </Image>
          </div>
        ))}
      </div>
    </CloudinaryContext>
   </section>
  );
 }
}

我的组件B接收道具。如果我console.log(this.props.location.state);在控制台中返回海报图像。如果我添加this.props.location.state.poster,则会收到错误:TypeError: cannot read property 'poster' of undefined。他是我的B部分。

class Topic extends Component{
 render() {
  const { poster } = this.props.location.state;
  return (
   <React.Fragment>
    <div style={{backgroundImage: `url(${poster})`}}>
      <h1>{this.props.match.params.topicId}</h1>
    </div>
   </React.Fragment>
  );
 }
}

任何帮助都会受到赞赏,因为我不明白为什么会这样。

0 个答案:

没有答案