React.js:应该由父级还是组件管理状态?

时间:2018-07-27 15:44:31

标签: javascript reactjs

我有一个“日期输入”组件,其中包含一个<input type="text">

目的是允许用户键入有效日期(例如, mm / dd / yyyy )。

一旦 ,用户输入有效日期,组件的父项应收到该日期。

基于此-我试图弄清楚组件还是父级应该管理状态。

如果我将其设置为 父级 来管理状态,

render() {
    return (
        <div>
            <input type="text" value={this.props.value} onChange={this.props.handleChange} />
        </div>
    );
}

...这不好,因为每次更改父母都会收到通知,并且在用户键入时将prop设置为所有“草稿”值(例如“ 07/2”)。

这表明我应该进行设置,以便 组件 管理其自身的状态:

class InputDateWithLabel extends Component {

    constructor(props) {
        super(props);

        this.state = {
            value: formatDate(this.props.value) // formatDate() formats a date object into an 'mm/dd/yyyy' string
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleBlur = this.handleBlur.bind(this);

    }

    handleChange(event) {
        // use setState() to update this.state.value so the <input> shows what the user types
    }

    handleBlur(event) {
        // if the user entered a valid date,
        // convert the user's input to a date object,
        // and communicate that to the parent. E.g.,:
        this.props.onChange([new date]);
        // Otherwise, handle the "error"
    }

    render() {
        return (
            <input type="text" value={this.state.value} onChange={this.handleChange} onBlur={this.handleBlur} />
        );
    }
}

此版本完全按照我想要的方式工作,除了另外一个要求 ...

根据我的应用程序中其他地方可能发生的情况,父级 可能需要在此组件中设置日期。但是-现在该组件正在管理自己的状态-当父级更改props.value时,我的组件将忽略它。

React文档在这里解决了这种情况:You Probably Don't Need Derived State

但是他们的解决方案似乎并不适用:

  

避免上述问题的一种方法是从组件中完全删除状态。

这不好,因为我不想让父母负责验证用户的日期输入。我的组件应该是独立的,包括日期验证,这意味着它需要管理用户输入的“草稿状态”。

  

另一种选择是让我们的组件完全拥有“草稿”状态。在这种情况下,我们的组件仍然可以接受初始值的支持,但会忽略对该支持的后续更改

这不好,因为我需要保留让父母在适当的时候更改值 的能力。

React文档的其余部分提到了其他一些可能性(getDerivedStateFromProps),但竭尽全力强调 它们可能不正确。 (请注意文章标题!)

这似乎并不罕见,因此必须有一种清晰,简单,有据可查的方法来处理它,这是正确的“反应方式”。那是什么?

1 个答案:

答案 0 :(得分:-1)

让组件管理自己的状态似乎并不坏,但是您将需要添加componentWillReceiveProps,这将添加另一段代码来管理。

comparing()
相关问题