嵌套的 React/Relay 组件不接收道具
Posted
技术标签:
【中文标题】嵌套的 React/Relay 组件不接收道具【英文标题】:Nested React/Relay component not receiving props 【发布时间】:2016-08-08 02:33:50 【问题描述】:我正在尝试将属性传递给另一个组件。将数组作为<VideoList videos=this.props.channel.video_list></VideoList>
传递会导致this.props.videos
成为一个空对象:
"videos":
"__dataID__": "client:5610611954",
"__fragments__":
"2::client": "client:5610611954"
(GraphQL 返回由 React Chrome 扩展程序确认的正确数据,只是没有传递到 VideoList
。)
components/video_list.js
import React from 'react'
import Relay from 'react-relay'
import VideoItem from '../containers/video_item'
export default class VideoList extends React.Component
render()
return(
<div>
this.props.videos.edges.map(video =>
<VideoItem key=video.id video=video.node/>
)
</div>
)
components/channel_list.js
import React from 'react'
import Relay from 'react-relay'
import VideoList from './video_list'
export default class ChannelView extends React.Component
render()
return(
<div>
<Column small=24>
<h2>this.props.channel.title</h2>
</Column>
<VideoList videos=this.props.channel.video_list></VideoList>
</div>
)
containers/channel_list.js
import React from 'react'
import Relay from 'react-relay'
import ChannelView from '../components/channel_view'
import VideoList from './video_list'
export default Relay.createContainer(ChannelView,
fragments:
channel: () => Relay.QL`
fragment on Channel
title
video_list
$VideoList.getFragment('videos')
`
,
);
containers/video_list.js
import React from 'react'
import Relay from 'react-relay'
import VideoList from '../components/video_list'
import VideoItem from './video_item'
export default Relay.createContainer(VideoList,
initialVariables:
count: 28
,
fragments:
videos: () => Relay.QL`
fragment on Videos
videos(first: $count)
pageInfo
hasPreviousPage
hasNextPage
edges
node
$VideoItem.getFragment('video')
`
,
);
我做错了什么?我是否误解了 Relay 的工作原理?我希望能够在VideoList
中设置count
中继变量以用于分页。 VideoList
对象将嵌套在多个其他组件中(例如频道、最受欢迎、用户的最爱等)
谢谢!
【问题讨论】:
【参考方案1】:您试图直接使用VideoList
组件,而没有中继容器包装它,这是错误的。
您需要使用 VideoList
包装版本 - 您在 ./containers/video_list.js
中导出的版本。
像这样:
import React from 'react'
import Relay from 'react-relay'
import VideoList from '../containers/video_list'
export default class ChannelView extends React.Component
render()
return(
<div>
<Column small=24>
<h2>this.props.channel.title</h2>
</Column>
<VideoList videos=this.props.channel.video_list></VideoList>
</div>
)
【讨论】:
谢谢!!哇,我觉得很傻!我一定已经搞砸了两个多小时,试图弄清楚我做错了什么。再次感谢安德烈! 这个答案在我挠了两个小时后救了我。谢谢!以上是关于嵌套的 React/Relay 组件不接收道具的主要内容,如果未能解决你的问题,请参考以下文章
为啥当我解构属性时接收道具的组件不起作用,但是当我使用 props.key 时它起作用了?