我想在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
})
}
})
}
}
答案 0 :(得分:1)
您可以使用.map
函数使用this.state.errors
迭代Object.keys(this.state.errors)
中的每个密钥:
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;