2017-03-15 23 views
0

ReactとReduxの初心者として、私はreact-datesをコンポーネントに使用しようとしています。Reduxを使用したコンポーネントの反応日

これは私のコードです:

import * as React from 'react'; 
import { connect } from 'react-redux'; 
import { ApplicationState } from '../store'; 
import * as DateState from '../store/Date'; 
import * as SingleDatePicker from 'react-dates'; 

type DateProps = DateState.DateState & typeof DateState.actionCreators; 

class DatePickerSingle extends React.Component<DateProps, any> { 

    public render() { 

     let { date } = this.props; 
     return (
      <div> 
       <SingleDatePicker 
        id="date_input" 
        date={this.props.date} 
        focused={this.state.focused} 
        onDateChange={(date) => { this.props.user({ date }); }} 
        onFocusChange={({ focused }) => { this.setState({ focused }); }} 
        isOutsideRange={() => false} 
        displayFormat="dddd LL"> 
       </SingleDatePicker> 
      </div> 
     ); 
    } 
} 

export default connect(
    (state: ApplicationState) => state.date, 
    DateState.actionCreators     
)(DatePickerSingle); 

これは、次のエラーを返します。

Exception: Call to Node module failed with error: TypeError: Cannot read property 'focused' of null 

focusedonFocusChangeは、私の知る限り理解として "DatePickerの状態を" 受けるべきです。

ドキュメント:

onFocusChange is the callback necessary to update the focus state in the parent component. It expects a single argument of the form { focused: PropTypes.bool }.

私はこの問題は、私がfocused状態について知らないDatePickerSingleコンポーネントにDateStateを注入することをだと思います。

自分の「独自の」状態とDatePickerの状態を一緒に使用できますか?または、最善のアプローチは何ですか?

私は今かなりの時間をかけています。誰かがこれを手伝ってくれることを願っています。

UPDATE

enter image description here

答えて

1

答えは非常に簡単です:それは初期化されていないためthis.stateはnullです。ただ、propsとしてあなたのコンポーネントに渡されますReduxのから来る

constructor() { 
    super(); 
    this.state = { 
    focused: false 
    } 
} 

何も追加し、あなたはそれに加えて、コンポーネントの状態を持つことができます。

+0

ありがとう@OlliM! 'Uncaught TypeError: 'getHostNode' of null'を読み込めません。Visual Studioの' this.setState({focused}) 'にカーソルを移動すると、まだ私の更新された質問のスクリーンショットを参照してください。 – JK87

+0

ええ、このエラーは解決されているようですが、このエラーが発生します: 'Exception:Nodeモジュールへの呼び出しがエラーで失敗しました:不変違反:要素タイプが無効です:文字列(組み込みコンポーネント用)またはクラス/関数(コンポジットコンポーネント用)ですがオブジェクトがあります。 'DatePickerSingle'のレンダリング方法を確認してください。 ' – JK87

+0

問題が見つかりました。 'singledatepicker'コンポーネントのdate属性は、Momentjs [link](https://momentjs.com/)オブジェクトを期待していました。私の減速機ではすでにフォーマットされているので、それは文字列になりました。すべてが期待通りに機能します。ご協力ありがとうございました! – JK87

関連する問題