我希望其子组件可以在其中注册父组件,因此我可以在其他位置使用此数据(例如,生成菜单)。
目前,我的代码如下:
const app = document.getElementById('app');
class Children extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.add(this.props.name);
}
render() {
return (
<div>Children</div>
)
}
}
class Items extends React.Component {
render() {
return (
<nav>
{this.props.content}
</nav>
)
}
}
class Parent extends React.Component {
constructor() {
super();
this.state = {
sections: []
}
}
add(section) {
const currentSections = this.state.sections;
const id = section.replace(' ', '-').toLowerCase();
const obj = { name: section, id };
this.setState({
sections: currentSections.push(obj)
});
}
render() {
console.log(this.state.sections);
return (
<div>
<Items content={this.state.sections} />
<Children add={this.add.bind(this)} name="Section 1" />
<Children add={this.add.bind(this)} name="Section 2" />
<Children add={this.add.bind(this)} name="Section 3" />
</div>
)
}
}
render(<Parent />, app);
我的问题是,this.state.sections
返回3
,但当我在componentDidMount
中再次登录时,它就是一个数组。
我该怎么办?
答案 0 :(得分:1)
add(section) {
const currentSections = this.state.sections;
const id = section.replace(' ', '-').toLowerCase();
const obj = { name: section, id };
currentSections.push(obj)
this.setState({
sections: currentSections
});
}
原因是你将state设置为currentSections.push(obj)实际上返回count而不是数组。先推,然后将这些部分设置为currentSections
答案 1 :(得分:0)
问题似乎是由于使用push
追加一个项目,该项目返回新元素的索引。
就地变异状态不是最佳选择,我认为最好使用concat
代替:
{
sections: currentSections.concat([obj])
}
将返回一个新数组。
在您的特定情况下,add
次调用之间也会出现竞争状态:三次回调将在大约同一时间被调用,因此在所有三次回调中{{1}将是currentSections
。然后每一个都会附加在item上并设置它,最终状态最终只包含一个元素,而不是三个。
为了缓解这种情况,您可以使用另一种方式调用[]
,确保所有三个按顺序添加:
setState