【发布时间】:2020-07-14 12:21:47
【问题描述】:
我是 React 语言的新手,遇到了涉及打印给定对象/数据结构的问题。
数据结构(JSON?)
{ "boards": [ { "groups": [ { "title": "Introduction" }, { "title": "Page Two" } ] } ] }
我可以打印this.state.boardData.boards 我找到了一些关于map() 功能的主题,但似乎无法让它工作。
我的 compentDidMount(涉及 monday.api 和 GraphQL):
monday.listen("context", res => {
this.setState({context: res.data});
monday.api(`query ($boardIds: [Int]) { boards (ids:$boardIds) { groups { title } } }`,
{ variables: {boardIds: this.state.context.boardIds} }
)
.then(res => {
this.setState({boardData: res.data});
});
})
我的 map() 函数:
const navItems = this.state.boardData.boards.map((title) =>
<a className="pageview__nav-item">{JSON.stringify(title, null, 2)}</a>
);
提供的错误:
TypeError: Cannot read property 'map' of undefined
我猜这是因为当我尝试映射值时这些值是空的。我试图初始化数据但没有运气:
constructor(props) {
super(props);
// Default state
this.state = {
settings: {},
name: "",
boardData: {groups: []}
};
}
我也尝试初始化变量,但这似乎在抱怨已经声明的变量。
谁能指出我正确的方向?那真的很有帮助。
【问题讨论】:
-
我找到了这个问题/答案,但可以真正将它整合到我自己的场景中。 stackoverflow.com/questions/24706267/…
-
我认为你可以在 map() 之前检查对象是否未定义(或 null、空)。 stackoverflow.com/questions/27509/…这会对你有所帮助。
标签: json reactjs jsx monday.com