【问题标题】:React component not making ajax call反应组件不进行ajax调用
【发布时间】:2016-08-24 08:56:52
【问题描述】:

我正在尝试实现一个组件,该组件处理对服务器的 ajax 请求并将数据传递给两个子组件。但是,似乎从未进行过ajax调用。

Feed.js:237 Uncaught TypeError: Cannot read property 'data' of null

是我得到的错误。

// Parent component containting feed and friends components,
// handles retrieving data for both

import React, { Component } from 'react'
import FeedBox from './Feed.js'
import FriendsBox from './Friends'

const config = require('../../config')

export default class FrontPage extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: {},
            pollInterval: config.pollInterval
        }
        this.loadDataFromServer = this.loadDataFromServer.bind(this)
    }

    loadDataFromServer() {
        $ajax({ 
            url: config.apiUrl + 'frontpage',
            dataType: 'jsonp',
            cache: false,
            success: (data) => {
                this.setState({data: data})
                console.log(data)
            },
            error: (xhr, status, err) => {
                console.error(this.url, status, error.toString())
            }
        })
    }
    componentDidMount() {
        this.loadDataFromServer()
        setInterval(this.loadDataFromServer, this.state.pollInterval)
    }
    componentWillUnmount() {
        this.state.pollInterval = false
    }
        render() {
            return (
                <div className="FrontPage">
                    <FeedBox data={ this.state.data.feedData } />
                    <FriendsBox data={ this.state.data.friendsData } />
                </div>
                )
        }
    }

编辑:

这里是 Feed 组件的代码,它是 FrontPage 的两个子组件之一,它正在从其父组件传递道具

import React, { Component } from 'react';

var config = require('../../config')

class Thread extends Component {
  rawMarkup() {
    var rawMarkup = marked(this.props.children.toString(), { sanitize: true })
    return {__html: rawMarkup }
  }

  render() {
    return (
      <div className="thread">
        <h4 className="threadVictim">Dear {this.props.victim}: </h4>
        <span dangerouslySetInnerHTML={this.rawMarkup()} />
        <p>signed,</p>
        <div>{this.props.author} and {this.props.ct} others.</div>
        <hr></hr>
      </div>
      )
  }
}

class ThreadList extends Component {
  render() {
    var threadNodes = this.props.data.map(function (thread) {
      return (
        <Thread victim={ thread.victim } author={ thread.author } ct={ thread.included.length } key={ thread._id }>
          { thread.text }
        </Thread>
      )
    })
    return (
      <div className="threadList">
        { threadNodes }
      </div>
      )
  }
}

var ThreadForm = React.createClass({

  getInitialState: function () {
    return {author: '', 
            text: '', 
            included: '',
            victim: '',
            ct: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author, 
                                text: text, 
                                included: included,
                                victim: victim
                              })
    this.setState({author: '', 
                  text: '', 
                  included: '',
                  victim: '',
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  // loadThreadsFromServer: function () {
  //   $.ajax({
  //     url: config.apiUrl + 'feed',
  //     dataType: 'jsonp',
  //     cache: false,
  //     success: function (data) {
  //       this.setState({data: data})
  //     }.bind(this),
  //     error: function (xhr, status, err) {
  //       console.error(this.url, status, err.toString())
  //     }.bind(this)
  //   })
  // },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: config.apiUrl + 'threads',
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.url, status, err.toString())
      }.bind(this)
    })
  },
  // getInitialState: function () {
  //   return {data: [],
  //           pollInterval: config.pollInterval}
  // },
  // componentDidMount: function () {
  //   this.loadThreadsFromServer()
  //   setInterval(this.loadThreadsFromServer, this.state.pollInterval)
  // },
  // componentWillUnmount: function () {
  //   this.state.pollInterval = false;
  // },
  render: function () {
    return (
    <div className="threadsBox">
      <div className="feedNav">
        <h1>Home</h1>
        <h1>Heat</h1>
      </div>
      <ThreadList data={ this.state.data } />
      <ThreadForm onThreadSubmit={ this.handleThreadSubmit } />
    </div>
    )
  }
})

module.exports = ThreadsBox

【问题讨论】:

  • setInterval(this.loadDataFromServer, this.state.pollInterval) 看起来不对。哪一行是错误的?
  • 最初您的this.state.data 是一个空数组,但您试图在render 函数中访问this.state.data.feedData,这意味着您希望它是一个对象。也许让状态结构更加清晰和一致。
  • @Kujira 谢谢我没有注意到,以前我返回一个数组,现在它确实是一个对象。我将其更改为 data = {},但我得到了同样的错误
  • 您能指定错误发生在哪一行吗?我的猜测是您将this.state.data.feedDatathis.state.data.friendsData 分别传递给FeedBoxFriendsBox,但它们最初是undefined,因为this.state.data 是空对象。您是否在这两个组件中都发现了这种基本情况?
  • @Kujira 是的,我相信是这样,因为在第一种情况下,父类没有进行 ajax 调用来获取数据,但我不知道为什么。错误行是

标签: javascript ajax node.js reactjs


【解决方案1】:

你需要在ThreadsBox中定义初始状态对象,所以它不是null

var ThreadsBox = React.createClass({
    getInitialState: function() {
      return {
        data: {}
      };
    }
    // ...
})
module.exports = ThreadsBox

【讨论】:

  • 通过阅读错误,您可以得出这个结论。 Cannot read property 'data' of null 表示“数据”之前的任何内容都不存在,无论是this.props.data 还是this.state.data。如果数据未定义,则错误会有所不同。
  • @devJunk 完全正确,读取错误加上错误行是 &lt;ThreadList data={ this.state.data } /&gt; 的注释 :-)
【解决方案2】:

ajax 调用未触发。尝试为请求添加方法:GET 或 POST。

【讨论】:

    猜你喜欢
    • 2015-09-10
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 2020-09-02
    • 2014-07-24
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多