2016-12-27 9 views
1

私は、子コンポーネントから親コンポーネント内のメソッド内の状態にアクセスしようとすると、私には未定義の値を返しますまず配列内にオブジェクトの値があることを確認してください。子から親にアクセスするときに未定義の状態になる - 反応

親コンポーネント:

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) 
    } 

この魔法は何ですか。.bindthisはJavaScriptで何を意味するのかを読んでおく必要があります。デフォルトでは、ES6のコンストラクタは自分の考えでは狂った理由でバインドしません。独自のメソッドを自分自身のthis値にバインドしません。したがって、お使いのメソッドのthisは、あなたが考えている、結果的に全く異なる、このシナリオを非常に奇妙なものにすることを意味しています。

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

+0

はい、バインディーです。私はes6が自動的に関数にバインドされないことを忘れていました。ありがとう! –

関連する問題