当使用React构建应用程序时,不应该使用枚举组件实例键来执行应用程序逻辑。这是因为React不能保证组件实例的键在每个渲染中都是稳定的。如果键发生更改,则可能导致React重复渲染组件。 相反,可以使用props或状态中的数据来执行应用程序逻辑。以下是一个基于枚举组件实例键的错误示例和一个使用props和状态的修复示例:
错误示例:
class MyComponent extends React.Component {
...
handleClick() {
const keys = Object.keys(this.refs);
keys.forEach((key) => {
const child = this.refs[key];
child.doSomething();
});
}
...
render() {
return (
);
}
}
修复示例:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
children: [],
};
}
handleClick() {
this.state.children.forEach((child) => {
child.doSomething();
});
}
render() {
return (
{this.state.children.map((child, index) => {
return { this.state.children[index] = el; }} />
})}
);
}
}
在这个修复示例中,组件状态存储了子组件的引用。当子组件被添加到父组件时,它们被推入到状态数组中。在处理点击事件时,父组件遍历状态数组并调用每个子组件的doSomething方法。总体效果与之前相同,但是我们不再依赖于枚举组件实例键来访问子组件。