ComponentDidMount 中的 for 循环,用于遍历不工作的对象



我有一个名为notes的道具,它是一个多层对象(如json(,来自某个父级。当我尝试在 ComponentDidMount 中遍历它时,它似乎不会进入循环内部,因为控制台日志没有输出任何内容。我错过了什么?

class NotesList extends React.Component {
state = {
arr: []
}

static defaultProps = {
notes: {
tier1: {
tier2: "some content 1",
tier22: "some 2"
},
tier11: {
tier222: "some content 1",
tier2222: "some 2"
}
}
}
componentDidMount() {
for (var folder in this.props.notes) {
console.log(folder);
this.state.arr.push(folder);
this.setState({
arr: this.state.arr
})
}
}
render() {
return (
<div>
something
</div>
)
}
}

注意:在这里,我将注释道具作为默认道具包含在内,以提供有关其结构的想法。实际上,它来自它的父母。但是那里没有问题。我检查了一下,我收到了正确的道具。

你不应该像this.props.notes那样多次设置状态,通过查看你的代码,你甚至不需要 for 循环,你可以像这样实现相同的结果:

componentDidMount() {
this.setState((prevState) => ({
arr: [...prevState.arr, ...this.props.notes]
}));
}

props 传递给你的构造函数,你需要在使用它们之前填充 this.props。只需添加...

constructor (props){
super(props);
// Any other initialisation you need
}

到你的班级

我明白了!

它不会进入for循环,因为this.props.notes是空的。 组件NotesList尚未收到道具,因为子组件的ComponentDidMount先于父项的ComponentDidMount运行。即将NotesList的道具是在父母的ComponentDidMount内获取的,我可能应该提到这一点。

最新更新