【问题标题】:What is the right construction to print this JSON data in React?在 React 中打印这个 JSON 数据的正确结构是什么?
【发布时间】: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: []}
        };
      } 

我也尝试初始化变量,但这似乎在抱怨已经声明的变量。

谁能指出我正确的方向?那真的很有帮助。

【问题讨论】:

标签: json reactjs jsx monday.com


【解决方案1】:

您正在尝试在 boardData 更新之前绘制地图。

因为这个:

构造函数(道具){ 超级(道具);

    // Default state
    this.state = {
      settings: {},
      name: "",
      boardData: {groups: []}
    };
  } 

在您的代码中:

const navItems = this.state.boardData.boards.map((title) =>
  <a className="pageview__nav-item">{JSON.stringify(title, null, 2)}</a>
);

this.state.boardData.boards 不存在,您会收到错误消息:

TypeError: Cannot read property 'map' of undefined

在渲染的 de return 中,您可以在使用地图之前进行验证,以确保该数组具有值。

按照您的 JSON 示例数据:

{ "boards": [ { "groups": [ { "title": "Introduction" }, { "title": "Page Two" } ] } ] }

您需要为每个板子提供一个地图,为板子内的每个组提供另一个地图以访问标题

return(
    <>
    {this.state.boardData.boards ? this.state.boardData.boards.map((group) =>
          <div className="groupContainer">
          {
            group.map(title=>
              <a className="pageview__nav-item">{title}</a>
            )
          }
          </div>
          }): null}
    </>
)

【讨论】:

  • 非常感谢您的选择,晚上晚些时候我会试试这个,是否也可以不使用“双重”映射?
  • 是的!如果您只收到组数组而不是板数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 2020-07-13
  • 1970-01-01
  • 2014-05-16
  • 1970-01-01
相关资源
最近更新 更多