【问题标题】:ReactJS this.props.data is undefinedReactJS this.props.data 未定义
【发布时间】:2015-09-21 17:53:36
【问题描述】:

我有两个类,officerModalsOfficerPhotoofficerModals 应该将数据传递给 OfficerPhoto。但是,当我尝试注销OfficerPhoto 中的数据时,我只会得到undefined。我一直在关注 Reacts 的教程,但我不知道哪里出了问题。有人可以帮忙吗?

reactReady = -> 
    officerModals = React.createClass
        getInitialState: ->
            {data: []}
        componentDidMount: ->            
            $.ajax
                url: this.props.url
                dataType: 'json'
                cache: false
                success:((data) ->
                    @setState data: data
                    # console.log data <- this logs the correct data
                    console.log @state.data.officers <- so does this
                ).bind(this)
        render: ->
            React.createElement 'div', { className: 'photos' }, React.createElement(OfficerPhoto, data: @state.data.officers)

    OfficerPhoto = React.createClass                  
        render: ->              
            React.createElement 'h1', {className: 'yes'}
        console.log 'test'                                      
        console.log @props #<- this returns undefined

    React.render React.createElement(officerModals, {url: "officers.json"}), $('#officerPics').get 0

$(document).ready reactReady
$(document).on 'page:load', reactReady

编辑:我在登录 @props 之前卡在了一个字符串中,并且我取消了 @state.data.officers 的注释。似乎officerPhoto 是在officerModals 之前渲染的——我该如何解决这个问题?

【问题讨论】:

    标签: javascript coffeescript reactjs


    【解决方案1】:

    这看起来像一个竞争条件。在渲染方法运行之前,您的 ajax 查询不会返回,因此 state.data.officers 是未定义的。

    【讨论】:

    • 但是他有setState方法,当数据到达时会重新渲染。我想是的。
    • 使用 chrome 调试器并在转译的代码上设置一些标记,以查看失败的地方。第一站是检查 ajax 承诺解决后的状态。
    • 在登录@props 之前,我卡在了一个随机字符串中,并且似乎OfficerPhotos 在officerModals 之前运行。我该如何解决这个问题?
    【解决方案2】:

    问题是officeModals 没有在OfficerPhoto 上传递道具。也许使用 Object.assign 会解决你的问题:

    React.createElement(OfficerPhoto, Object.assign({}, this.props, { data: 'values' }));
    

    【讨论】:

    • 我按照你的建议尝试了,但不幸的是它没有用
    猜你喜欢
    • 2015-09-28
    • 2016-09-01
    • 2016-05-22
    • 1970-01-01
    • 2016-05-06
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    相关资源
    最近更新 更多