【发布时间】:2018-09-18 07:48:04
【问题描述】:
如何使用基于 props 的动态键初始化 state? props 是从外部源(异步)获取的数据。因此,当数据成功下载时,道具会发生变化。考虑这样的组件。
编辑:我想使状态动态化,因为我想根据单击的项目生成一个对话框(弹出)。 DialogContainer 基本上就是这样。 visible prop 将使该对话框可见,而 onHide prop 将隐藏该对话框。我用react-md library。
class SomeComponent extends React.Component {
constructor() {
super();
this.state = {};
// the key and value will be dynamically generated, with a loop on the props
// something like:
for (const item of this.props.data) {
this.state[`dialog-visible-${this.props.item.id}`] = false}
}
}
show(id) {
this.setState({ [`dialog-visible-${id}`]: true });
}
hide(id) {
this.setState({ [`dialog-visible-${id}`]: false });
}
render() {
return (
<div>
{this.props.data.map((item) => {
return (
<div>
<div key={item.id} onClick={this.show(item.id)}>
<h2> Show Dialog on item-{item.id}</h2>
</div>
<DialogContainer
visible={this.state[`dialog-visible-${item.id}`]}
onHide={this.hide(item.id)}
>
<div>
<h1> A Dialog that will pop up </h1>
</div>
</DialogContainer>
</div>
);
})}
</div>
)
}
}
// the data is fetched by other component.
class OtherComponent extends React.Component {
componentDidMount() {
// fetchData come from redux container (mapDispatchToProps)
this.props.fetchData('https://someUrlToFetchJSONData/')
}
}
然后通过 Redux 共享数据。
但是,根据我目前的理解,可以使用 componentWillReceiveProps 或新的 getDerivedStateFromProps(而不是上面的构造函数)基于 props 更新状态。但是,如何在这两种方法上做到这一点?
示例here 仅解释了何时在构造函数上初始化状态,并在 cWRP 或 gDSFP 上调用 setState。但是,我希望动态初始化键值对。
任何帮助/提示将不胜感激。如果我的问题不够清楚,请务必指出。
【问题讨论】:
-
当你在构造函数中运行
for loop时,props.data应该是redux提供的吗? -
是的。就是这样。
-
而你想使用redux提供的状态。你问的对吗?
-
不是直接的。我添加了一些细节。让我先了解你的答案。编辑:我了解如何使用 connect() 连接状态。但我想用来自该数据的信息生成另一个状态。不是直接的。谢谢!
-
为什么不能在动作本身中创建您希望它们出现的状态?然后你可以通过
render()函数映射它们
标签: javascript reactjs javascript-objects computed-properties