2017-07-28 41 views
0

这是演示文件:阵营国家设置后未定义在componentDidMount

import React, { Component } from 'react' 

class CreateZone extends Component { 
    constructor(){ 
     super() 
      this.state = { 
       zone: { 
        name: '', 
        zipCodes: [] 
       } 
      } 
    } 

    newZone(event){ 
     let newZone = Object.assign({}, this.state.zone) 
     newZone[event.target.id] = event.target.value 
     this.setState({ 
      zone: newZone 
     }) 
    } 
    submitZone(event){ 
     this.props.onCreate(this.state.zone) 
    } 

    render(){ 
     return(
      <div> 
      <input id="name" onChange={this.newZone.bind(this)} className="form-control" type="text" placeholder="Enter Zone Name" /><br /> 
      <input id="zipCodes" onChange={this.newZone.bind(this)} className="form-control" type="text" placeholder="Enter Zip Code" /><br /> 
      <button onClick={this.submitZone.bind(this)} className="btn btn-danger">Submit Comment</button> 
      </div> 
     ) 
    } 
} 
export default CreateZone 

这是容器文件:

import React, { Component } from 'react' 
import { Zone, CreateZone } from '../presentation' 
import { APImanager } from '../../utils' 

class Zones extends Component { 
    constructor(){ 
     super() 
     this.state = { 
      zone: { 
       name: '', 
       zipCodes: '', 
       numComments: '' 
      }, 
      list: [] 
     } 
    } 

    componentDidMount(){ 
     console.log('componentDidMount') 
     APImanager.get('/api/zone', null, (err, response) => { 
      if(err){ 
       alert('Error in zones: '+err.message) 
       return 
      } 

      this.setState({ 
       list: response.results 
      }) 
     }) 
    } 

    submitZone(zone){ 
     let newZone = Object.assign({}, zone) 

     APImanager.post('/api/zone', newZone, (err, response) => { 
      if(err) { 
       alert('ERROR in New Zone: '+err.message) 
       return 
      } 
      console.log('NewZone: '+JSON.stringify(response)) 
      let updatedList = Object.assign([], this.state.list) 
      updatedList.push(response.result) 
      this.setState({ 
       list: updatedList 
      }) 


     }) 
    } 

    render(){ 

     const listItems = this.state.list.map((zone, i) => { 
      return (
       <li key={i}> 
        <Zone currentZone={zone} /> 
       </li> 
      ) 
     }) 

     return(
      <div> 
       <ol> 
        {listItems} 
       </ol> 
       <div> 
        <CreateZone onCreate={this.submitZone} /> 
       </div> 
      </div> 
     ) 
    } 
} 
export default Zones 

阵营不会重新渲染和控制台日志错误是“无法读取属性未定义的“列表” 在将表单移入演示文稿文件之前它工作正常。这是我的训练,我很想知道发生了什么

回答

1

区域组件中的submitZone函数没有得到“this”绑定。所以它将“this.state”定义为undefined。绑定 “这种” 相同

<button onClick={this.submitZone.bind(this)} className="btn btn-danger">Submit Comment</button> 

因此,与

<CreateZone onCreate={this.submitZone.bind(this)} /> 
+0

更换线

<CreateZone onCreate={this.submitZone} /> 

感谢你,帮助 – eddbreuer