Javascript React组件不进行ajax调用

Javascript React组件不进行ajax调用,javascript,ajax,node.js,reactjs,Javascript,Ajax,Node.js,Reactjs,我试图实现一个组件,该组件处理对服务器的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, { Com

我试图实现一个组件,该组件处理对服务器的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>
                )
        }
    }
//包含提要和好友组件的父组件,
//处理检索这两个数据库的数据
从“React”导入React,{Component}
从“./Feed.js”导入FeedBox
从“./Friends”导入FriendsBox
const config=require(“../../config”)
导出默认类FrontPage扩展组件{
建造师(道具){
超级(道具)
此.state={
数据:{},
pollInterval:config.pollInterval
}
this.loadDataFromServer=this.loadDataFromServer.bind(this)
}
loadDataFromServer(){
$ajax({
url:config.apiUrl+“frontpage”,
数据类型:“jsonp”,
cache:false,
成功:(数据)=>{
this.setState({data:data})
console.log(数据)
},
错误:(xhr、状态、错误)=>{
console.error(this.url,status,error.toString())
}
})
}
componentDidMount(){
这是loadDataFromServer()
setInterval(this.loadDataFromServer,this.state.pollInterval)
}
组件将卸载(){
this.state.pollInterval=false
}
render(){
返回(
)
}
}
编辑:

下面是提要组件的代码,它是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
import React,{Component}来自'React';
var config=require(“../../config”)
类线程扩展组件{
rawMarkup(){
var rawMarkup=marked(this.props.children.toString(),{sanitize:true})
返回{uuu html:rawMarkup}
}
render(){
返回(
亲爱的{this.props.被害人}:
签字

{this.props.author}和{this.props.ct}其他。
) } } 类ThreadList扩展组件{ render(){ var threadNodes=this.props.data.map(函数(线程){ 返回( {thread.text} ) }) 返回( {threadNodes} ) } } var ThreadForm=React.createClass({ getInitialState:函数(){ 返回{作者:“”, 文本:“”, 包括:'', 受害者:“, ct:' } }, handleAuthorChange:函数(e){ this.setState({author:e.target.value}) }, handleTextChange:函数(e){ this.setState({text:e.target.value}) }, HandleIncludeChange:函数(e){ this.setState({包括:e.target.value}) }, handleVictimChange:函数(e){ this.setState({牺牲品:e.target.value}) }, handleSubmit:函数(e){ e、 预防默认值() var author=this.state.author.trim() var text=this.state.text.trim() var included=this.state.included.trim() var-victor=this.state.victor.trim() 如果(!text | | |!作者| |!包括| |!受害者){ 返回 } this.props.onThreadSubmit({作者:作者, 文本:文本, 包括:包括,, 受害者:受害者 }) 此.setState({作者:“”, 文本:“”, 包括:'', 受害者:“, }) }, 渲染:函数(){ 返回( ) } }) var ThreadsBox=React.createClass({ //loadThreadsFromServer:函数(){ //$.ajax({ //url:config.apiUrl+'feed', //数据类型:“jsonp”, //cache:false, //成功:功能(数据){ //this.setState({data:data}) //}.bind(这个), //错误:函数(xhr、状态、错误){ //console.error(this.url,status,err.toString()) //}.bind(这个) // }) // }, HandletThreadSubmit:函数(线程){ var threads=this.state.data var newThreads=threads.concat([thread]) this.setState({data:newThreads}) $.ajax({ url:config.apiUrl+“线程”, 数据类型:“json”, 键入:“POST”, 数据:线程, 成功:功能(数据){ this.setState({data:data}) }.绑定(此), 错误:函数(xhr、状态、错误){ this.setState({data:threads}) console.error(this.url,status,err.toString()) }.绑定(此) }) }, //getInitialState:函数(){ //返回{数据:[], //pollInterval:config.pollInterval} // }, //componentDidMount:函数(){ //this.loadThreadsFromServer() //setInterval(this.loadThreadsFromServer、this.state.pollInterval) // }, //componentWillUnmount:函数(){ //this.state.pollInterval=false; // }, 渲染:函数(){ 返回( 家 热度 ) } }) module.exports=ThreadsBox
您需要在
ThreadsBox
中定义初始状态对象,使其不为
null

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

您需要在
ThreadsBox
中定义初始状态对象,使其不为
null

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

ajax调用没有启动。尝试为请求添加方法:GET或POST

ajax调用没有启动。尝试为请求添加方法:GET或POST

setInterval(this.loadDataFromServer,this.state.pollInterval)
看起来有误。哪一行是错误行?最初您的
this.state.data
是一个空数组,但您正在尝试访问
render
函数中的
this.state.data.feedData
,这意味着您希望它是一个对象。也许能让国家结构更加清晰一致。@Kuj