繁体   English   中英

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

[英]React.js: Should parent or component manage state?

我有一个“日期输入”组件,其中包含一个<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文档在这里解决了这种情况: 您可能不需要派生状态

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

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

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

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

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

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

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

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

componentWillReceiveProps(nextProps) {
    this.setState({
        value: formatDate(nextProps.value)
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM