我是React World的新手,目前正在尝试使用AJV JSON-Schema Validator。当用户上传Json文件时,我将其存储到状态。然后提交后我运行了验证器。它虽然在cosole.log中显示数据,但它不起作用。此外,如果我将json硬编码为如下状态:
state = {
file: {"foo": 2, "bar": 4}
}
然后它工作正常。我的代码:
import React from 'react';
let Ajv = require('ajv');
// import axios from 'axios';
class Form extends React.Component {
state = {
file: '',
}
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.file)
let ajv = new Ajv({ allErrors: true });
//Validation Rule
let validate = ajv.compile(
{
"properties": {
"foo": { "type": "string" },
"bar": { "type": "number", "maximum": 3 }
}
}
);
let valid = validate(this.state.file);
if (valid) {
console.log('Valid!');
} else {
console.log('Invalid: ' + ajv.errorsText(validate.errors));
}
}
// Handle Upload Using FileReader
handleFile = (e) => {
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = (event) => {
console.log(event.target.result);
this.setState({
file: event.target.result
});
}
reader.readAsText(file)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="file" onChange={this.handleFile}/>
<button>Submit</button>
</form>
)
}
}
我的Json数据:
{"foo": 2, "bar": 4}