当用户点击某个项目时,我正在尝试将我的应用中的视频设置为“精选”。我有一个 Action 创建器,它在调用时执行一个简单的 console.log(),为了测试,我将其称为 w/componentDidMount()
,它工作正常。我有一个单独的 VideoItem 组件,我试图传递 Action 创建者,但我收到错误:TypeError: Cannot read property 'props' of undefined
。我尝试将 .bind(this)
添加到我传递的操作的末尾,但没有任何区别。
如果当我在 componentDidMount
调用它时 action creator 工作,为什么我不能将它传递给子组件?这是我的 Video 和 VideoItem 组件:
// Video.js
import React, { Component } from 'react'
import VideoItem from './VideoItem'
class Videos extends Component {
componentDidMount() {
this.props.actions.getVideos()
// This function works, but getting error
// when passing to VideoItem component
this.props.actions.setFeaturedVideo()
}
constructor(props) {
super(props);
}
render() {
if(this.props.videos.length == 0){
return <p>Loading....</p>
}
return (
<div className="container">
<ul className="row">
{this.props.videos.map(function(result) {
return (
<VideoItem
key={result.position}
setFeaturedVideo={this.props.setFeaturedVideo}
video={result}
/>
)
})}
</ul>
</div>
)
}
}
export default Videos
// VideoItem.js
import React, { Component } from 'react'
class VideoItem extends Component {
constructor(props) {
super(props);
}
render() {
return (
<li className="col m6" onClick={this.props.setFeaturedVideo()}>
{this.props.video.title}
</li>
)
}
}
export default VideoItem
最佳答案
错过了 map 函数中的 this。由于您使用的是 map ,因此“this”属于 map 功能。您需要在 map 函数之前将它分配给一个变量,然后使用它。
render() {
var _that = this;
if(this.props.videos.length == 0){
return <p>Loading....</p>
}
return (
<div className="container">
<ul className="row">
{this.props.videos.map(function(result) {
return (
<VideoIte
key={result.position}
setFeaturedVideo={_that.props.actions.setFeaturedVideo}
video={result}
/>
)
})}
</ul>
</div>
)
}
关于javascript - 使用 props 将 Redux Action 传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36252126/