gpt4 book ai didi

javascript - 在 ReactJS 中打开模式对话框时,如何使用 prop 来定义模式对话框的初始状态?

转载 作者:行者123 更新时间:2023-12-02 15:43:06 25 4
gpt4 key购买 nike

我读了很多文章,在 React 中,将 prop 绑定(bind)到状态是一种反模式,我也有这种感觉。但我想创建一个模式对话框,打开该对话框时,它将使用 Prop 来定义对话框的惯性状态。因此,在这个 Prop 中,我将传入一个 People 对象列表,我的对话框将创建一个可编辑的表单,每个人都有一行。

var peopleList = [
{name: "person1", address: "address1"},
{name: "person2", address: "address2"}
];

<Dialog people={peopleList} />

它需要将 Prop 存储到它的状态中。但是此对话框将有一个按钮,用于在表单中创建更多行以输入有关更多人的数据。按下此按钮将导致对话框中的状态发生变化,但对话框 Prop 所基于的数据不会改变。由于对话框是模态的,这真的是一件坏事吗?

最佳答案

根据文档:

However, it's not an anti-pattern if you make it clear that synchronization's not the goal here

“这里”指的是以下代码:

var Counter = React.createClass({
getInitialState: function() {
// naming it initialX clearly indicates that the only purpose
// of the passed down prop is to initialize something internally
return {count: this.props.initialCount};
},

handleClick: function() {
this.setState({count: this.state.count + 1});
},

render: function() {
return <div onClick={this.handleClick}>{this.state.count}</div>;
}
});

React.render(<Counter initialCount={7}/>, mountNode);

正如您在此处所看到的,您不应将预期属性命名为 count(从语义上讲,这意味着一个始终保持静态的属性),而是将其称为 initialCount 来指示该属性最终会随着时间的推移而改变,并且不是反模式。

因此,在您的代码中,不要将预期的 people 属性命名为 people,而是将其命名为 initialPeopleList

顺便说一句,我注意到您正在传递 peopleList 的非复制引用。只需确保您的组件不会直接修改 peopleList 的内容,而是为每次修改返回一个新副本。

// THIS IS BAD! REALLY BAD!

push(person) {

// This is modifying the list directly!
// Don't do this!
this.state.people.push(person);

this.setState({
people: this.state.people
});

}

// -------------------------

// THIS IS MUCH BETTER!

push(person) {
this.setState({
// `concat` returns a new copy, leaving the original intact!
people: this.state.people.concat([person]);
})
}

关于javascript - 在 ReactJS 中打开模式对话框时,如何使用 prop 来定义模式对话框的初始状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32428827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com