【问题标题】:How can i display errors in react ; i am getting the array errors from redux? [duplicate]我如何在反应中显示错误;我从 redux 得到数组错误? [复制]
【发布时间】:2018-12-01 14:49:04
【问题描述】:

这是我从后端节点 js api 获得的 redux 数组

errors:
errors: Array(1)
0: {location: "body", param: "name", value: "mamadou bah transfert", msg: "ce nom est déja utilisé"}
length: 1

在 React 中我试图显示这样的错误

<div class="col m12">
  {this.props.offices.errors.errors?
  <span className="center-align red-text">
			{this.props.offices.errors.errors.map((error,i) => <p key={i}>       {error.param=='name'?error.msg:''}</p>) 
      </span> : '' }
</div>

这是我经常遇到的错误

react-errors

【问题讨论】:

  • 执行console.log(this.props.offices) 并在此处写入输出。然后我可以帮助您,因为我需要查看您的对象/列表的结构。
  • 您错误中的代码与您问题中的代码不匹配。 this.props.offices.errors ? this.props.offices.errors.errors ? .

标签: javascript reactjs redux


【解决方案1】:

由于errors 来自异步请求,您应该保护对象尚不存在的情况。

this.props.offices &amp;&amp; this.props.offices.errors.errors.map(...)

但是为了 100% 确定它不会失败,我将使用默认值 offices 并检查 errors 是否存在并且它是一个可迭代数组。

const { offices = {} } = this.props;

offices.errors && Array.isArray(offices.errors.errors) && offices.errors.errors.map(...);

【讨论】:

  • 这就是重点:)
【解决方案2】:

试试这个

关键是当你想访问嵌套对象时,你需要先检查嵌套对象是否真的存在,然后像下面的条件检查一样访问它

  <div class="col m12">
        {this.props.offices && this.props.offices.errors && this.props.offices.errors.errors?
           <span className="center-align red-text">
        {this.props.offices.errors.errors.map((error,i) => <p key={"Key-"+i}>       {error.param=='name'?error.msg:''}</p>) 
           </span> : '' }
   </div>

【讨论】:

    猜你喜欢
    • 2018-04-09
    • 2021-08-01
    • 2022-11-07
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2019-05-18
    相关资源
    最近更新 更多