2016-12-27 86 views
1

我有一個問題,在我要從我的子組件中訪問父組件內的方法的狀態時,它會返回一個未定義的值,首先肯定有一個數組中的對象的值。從兒童到父母訪問時獲取未定義的狀態 - React

父組件:

class BoardList extends React.Component { 
    constructor(props){ 
     super(props); 

     this.state = { 
      lists: [] 
     }; 
    } 

    componentWillMount(){ 
     this.props.getBoardLists() 
     .then((result) => { 
      this.setState({ 
       lists: result 
      }); 
     }) 
     .catch(error => { 
      console.log(error); 
     }); 
    } 

    addBoardLists(result){ 
     // This is i'm getting my undefine state lists :(
     console.log(this.state.lists); 
     this.setState({ 
      lists: this.state.lists.concat([result]) 
     }); 
    } 

    render() { 

     const { isLoading,data } = this.props; 

     if(isLoading){ 
      return (
       <Loading /> 
      ); 
     } 

     return (
      <div className={style.boardListContainer}> 
       <h1 className={style.boardListTitle}>Personal Board</h1> 
       <Row> 
        <BoardItem item={this.state.lists} /> 
        <BoardAdd onDisplay={this.fetchBoardLists} onAddItem={this.addBoardLists} /> 
       </Row> 
      </div> 
     ) 
    } 
} 

子組件:

class BoardAdd extends React.Component { 

    constructor(props){ 
     super(props); 

     this.state = { 
      name: '', 
      boardAddModalShow: false 
     } 

    } 

    openAddBoardModal(){ 
     this.setState({ boardAddModalShow: true }); 

    } 

    closeAddBoardModal(){ 
     this.setState({ boardAddModalShow: false }); 
     this.props.dispatch(reset('BoardAddModalForm')); 
    } 

    addBoard(formProps) { 
     this.props.addBoard(formProps).then((result) => { 
      // This is where I access my addOnItem from my parent component 
      this.props.onAddItem(result); 
      this.props.dispatch(reset('BoardAddModalForm')); 
      this.closeAddBoardModal(); 
     }) 
     .catch(error => { 
      console.log("error"); 
      console.log(error); 
     }); 
    } 
} 

回答

2

或許這將幫助?

class BoardList extends React.Component { 
    constructor(props){ 
     super(props); 

     this.state = { 
      lists: [] 
     }; 
     this.addBoardList.bind(this) 
    } 

這是什麼神奇的.bind?你應該閱讀什麼this在JavaScript中的含義(它幾乎從不認爲你的想法是什麼意思)。默認情況下,ES6的構造函數不會綁定(在我看來有些瘋狂的原因),他們自己的方法會自己的this值。因此,您的方法中的this指的是您正在考慮的並且相應地完全不同的this,這使得這種情況非常奇怪。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this

+0

是其結合啄。我忘記了es6不會自動綁定功能。謝啦! –