![](/img/trans.png)
[英]ReactJs - Redux State is not updating in a dropdown in the child component
[英]ReactJS component state dropdown not updating
我有一个包含移动设备列表的 reactjs 自定义下拉组件。
最初渲染了三个组件实例。
我想从其他下拉列表中删除选定的手机
例如,假设主移动列表包含 Apple、Nokia、Samsung 和 OnePlus。
如果您在第一个下拉列表中选择诺基亚,那么在第二个下拉列表中您应该会看到列表中的手机,但没有诺基亚。
您可以将下拉列表的选项保持在状态,并为每个下拉列表的选项保持不同的状态
我会这样处理
1.有一个父容器呈现3个下拉子组件。
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
child1: ['samsung', 'sony'],
child2: ['samsung', 'sony'],
child3: ['samsung', 'sony'],
}
}
render()
return(
<div> // see below for handleSelect function
<Dropdown onSelect={this.handleSelect.bind(this)} selectables={this.state.child1} />
<Dropdown onSelect={this.handleSelect.bind(this)} selectables={this.state.child2} />
<Dropdown onSelect={this.handleSelect.bind(this)} selectables={this.state.child3} />
<div>
)
}
2.在父容器中,创建一个函数,该函数将在选择子项的下拉选项时触发。 例如)
// In parent container
handleSelect(object) {
// Do logic here.
// e.g. if the first child selects an option by
if (object.selectedChild === 'FIRST')
const selected = object.selected;
// remove selected from an array
this.setState({ ... update the second dropdown selectables });
}
// In child component. Call this when option is selected
handleSelect(value) {
const obj = { selectedChild: 'FIRST' , selected: value };
this.props.onSelect(obj); // call parent function
}
3.当孩子打电话时
this.props.onSelect(obj)
它将相应地更新父级中的状态,这将在重新渲染时将更新的 props 传递给子级
然后孩子将使用更新的可选对象重新渲染。
我只能用状态形状来帮助你。 组件处理应该是你自己的工作。
您可以为下拉列表使用共享状态。 您将在哪里存储一系列项目并跟踪所选项目。
例如在容器中的某处:
state = {
data: [
{
name: 'Nokia',
selected: false,
},
{
name: 'Apple',
selected: false,
},
{
name: 'OnePlus',
selected: false,
}
]
}
在您的下拉组件中,使用.filter()
简单过滤此数组,如下所示:
this.state.data.filter((item) => !item.selected)
处理下拉标签的选择逻辑和选定项应该不成问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.