国家反模式的道具

时间:2016-10-27 07:19:50

标签: reactjs

所以我正在阅读反应文档,建议在状态中使用道具被认为是反模式。我想知道写的方式是什么。我有一个父状态容器将数据传递给一个也有状态的子组件。

constructor(props) {
  this.state = {
    name = this.props.name
  }
}

所以我想知道如果我更新CDM方法中的状态

constructor(props) {
  this.state = {
    name = ''
  }
}

componentDidMount() {
  this.setState({name : this.props.name})
}

这里的任何帮助或讨论都将不胜感激。

1 个答案:

答案 0 :(得分:0)

在州内使用道具是一个很大的禁忌。这是一个如何处理这些情况的例子

class Parent extends Component {
    state = {
        name: 'John Doe'
    }

    updateName = (name) => {
        this.setState({ name });
    };

    render() {
        return (
           <div>
                <label>Your Name</label>
                <Input value={this.state.name} updateName={this.updateName} />
           </div>
        );
    }
}

class Input extends Component {
    handleUpdate = (e) => {
        this.props.updateName(e.target.value);
    };

    render() {
        return <input value={this.props.value} onChange={this.handleUpdate} />
    }   
}