0

作为 React 和 Redux 的新手,我正在尝试在组件中使用react-dates

这是我的代码:

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据我了解,应该收到“日期选择器状态” 。

文件:

onFocusChange 是更新父组件中焦点状态所必需的回调。它需要一个 {focused: PropTypes.bool} 形式的参数。

我认为问题在于我DateStateDatePickerSingle组件中注入了不知道focused状态的组件。

是否可以同时使用我的“自己的”状态和 DatePicker 中的状态?或者最好的方法是什么?

我现在正在尝试很长一段时间,我希望有人可以帮助我。

更新

在此处输入图像描述

4

1 回答 1

1

答案很简单:this.state是 null 因为它还没有被初始化。只需添加

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

来自 redux 的任何内容都将作为 传递给您的组件props,除此之外,您还可以拥有组件状态。

于 2017-03-16T13:25:09.220 回答