我们如何在ReactJS渲染中显示Laravel Validation响应?

时间:2018-05-15 17:46:51

标签: laravel reactjs laravel-5 axios laravel-5.6

我想在ReactJS rendor函数中显示laravel验证列表。 我得到了以下回应。

{"message":"The given data was invalid.","errors":{"phone_number":["The phone number field is required."],"group_id":["The group id field is required."]}}

我不知道如何在reactJS rendor中显示如下所示的错误。

@if($errors->has())
  <ul>
   @foreach ($errors->all() as $error)
      <li>{{ $error }}</li>
  @endforeach
 </ul>
@endif

这是我的axios api表单句柄功能。

 handleSubmit(e){
    e.preventDefault();
    console.log(this.state);

    if(this.state.action === "add"){
        axios.post('/api/add', this.state).then(response => {

                alert("Data Success inserted")

        }).catch(error => {
            if(error.response.status == 422){
                // alert("Errors...");
                this.setState({
                    errors: error.response.data.errors
                })
            }
        })
    }
  }

1 个答案:

答案 0 :(得分:1)

您可以使用.map函数使用this.state.errors迭代Object.keys(this.state.errors)中的每个密钥:

&#13;
&#13;
class Errors extends React.Component {
  
  state = {
    errors: {"message":"The given data was invalid.","errors":{"phone_number":["The phone number field is required."],"group_id":["The group id field is required."]}}
  };
  
  renderErrors = () => {
    const { errors } = this.state;
    
    const errorItems = Object.keys(errors.errors).map( (key, i) => {
      const error = errors.errors[key][0];
      return (
        <li>
          {key}:<br/>
          {error}
        </li>
      )
      
    });
    
    return (
      <ul>
        {errorItems}
      </ul>
    )
    
  };

  render () {
    const errors = this.renderErrors();
    return (
      <div>
        {this.state.errors && this.state.errors.message}<br/>
        {errors}
      </div>
    )
  }
}

ReactDOM.render(<Errors />, document.querySelector('#root'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
&#13;
&#13;