2017-08-04 7 views
-1

私は、Text-FieldのMaterial-ui react jsコンポーネントです。私はredux形式を使用していません。ReactJS - this.props.reducer.result.firstNameからのデータをバインドした後に入力フィールドを編集できません。

私は状態だけでなく、私は減速機能を介して、小道具から受け取った値を用いて、入力要素の値を更新するかどうかはわかりませんのonchange listernerと状態

constructor(props) { 
    super(props); 
    this.state = { 
    firstName: null, 
    }; 
    this.handleInputChange = this.handleInputChange.bind(this); 
} 

componentDidMount() { 
    // This is reducer function to get my data from server. I'm getting data and able to display it to my element. 
    // I'm using redux for my data layer. 
    this.props.getuserDetails(userId); 
} 

を宣言しました。

handleInputChange (event) {} 
    this.setState({ 
    firstName: event.target.value 
    }); 
} 

my render関数内。 テキストフィールドには、ユーザーのfirstnameが表示されます。しかし、私はフィールドを編集することができません。私はprops.reducerを直接バインドしているからです。

<TextField name="firstName" onChange={this.handleInputChange} floatingLabelText="First Name" value={this.props.reducer.result.firstName}/> 

は、どのように私は、ディスパッチャ/減速からデータをバインドします。また、ユーザー入力を受け入れて名を編集します。 後でサーバーで更新できます

私はこの問題を抱えています。どんな助けもありがとう。ありがとう。

答えて

1

componentDidMountの後に、this.props.getuserDetails(userId)関数が再び小道具を設定します。componentWillReceivePropsに状態を設定する必要があります。代わりに、this.props.reducer.result.firstname

コードのthis.state.firstnameを使用します。

componentWillReceiveProps(nextProps){ 
    if(this.state.firstName != nextProps.reducer.result.firstname) 
    { 
     this.setState({ 
      firstName: nextProps.reducer.result.firstname 
     }); 
    } 
} 

これはpropsstateに更新されますし、あなたが正しいthis.state.firstname

<TextField name="firstName" onChange={this.handleInputChange} floatingLabelText="First Name" value={this.state.firstName}/> 
+0

ありがとうございます。出来た。以前は、以下のメソッドで状態値を設定しようとしましたが、失敗しました。componentWillReceiveProps(){] – PremPalanisamy

1

を使用しています。入力要素をsetState()で更新することはできません。これは、その値が小道具を介して伝達され、小道具に拘束されているためです。例えば::

handleInputChange (e) {} 
    // NOTE: I just made up this action 
    this.props.setUserDetails(e.target.value); 
} 
  • たびに、あなたの入力変更をアクションを派遣することにより

    あなたが達成しようとしている内容に応じて、利用できるさまざまなソリューションがあります。..

    1. 更新小道具initialStateをpropsから設定し、入力を状態にバインドします(これは反パターンと見なされますが、初期状態でのみ使用されていることを明確にすると問題ありません)。 ):

      componentDidMount() { 
          this.setState({ value: this.props.value }) 
      } 
      
      handleInputChange (e) {} 
          this.props.setState({ value: e.target.value }); 
      } 
      
    2. 小道具が変わるたびに、小道具と状態をマージします。

    3. ...

    しかし、いずれにせよ前に言ったように、それはあなたが何をしようとしているかに依存します。

    Here's a more detailed answer

  • 関連する問題