将Redux Action传递给带有props的子组件

Mik*_*ike 3 javascript flux reactjs reactjs-flux redux

我想在用户点击某个项目时将我的应用中的视频设置为"精选".我有一个动作创建者在调用时执行一个简单的console.log(),并且为了测试我调用它w/componentDidMount(),它工作正常.我有一个单独的VideoItem组件,我试图传递动作创建者,但我得到一个错误:TypeError: Cannot read property 'props' of undefined.我试图添加.bind(this)到我传递的动作的结尾,但它没有任何区别.

如果动作创建者在我调用时工作componentDidMount,为什么我不能将它传递给子组件?这是我的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
Run Code Online (Sandbox Code Playgroud)

Nor*_*all 5

错过了这个里面的地图功能.由于您使用的是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>
)
Run Code Online (Sandbox Code Playgroud)

}

  • Norm也提到了我所接受的内容,这应该是它的本质.不过,看起来你正在使用ES6.你可以破坏你的道具,这样你就不必做像`_that`这样的事情.相反,你可以在render方法的顶部放置`const {actions,videos} = this.props`.然后,无论你在哪里使用`this.props.*`,只需直接调用它.例如,`videos.map(result => <VideoItem key = {result.position} setFeaturedVideo = {actions.setFeaturedVideo} video = {result})` (3认同)
  • 另外一个注意事项 - 因为你正在使用Redux(我假设基于动作),而不是检查`videos.length === 0`,你可以将`isLoading`作为状态的一部分 - 然后当事物被加载时,你发送一个动作来将`isLoading`从true更新为false并让事情相应地重新流动. (3认同)