我正在接受用户的输入,并检查其是否采用正确的json格式,或者逻辑是否工作正常。错误是如果用户正确输入正确的格式或连续输入错误的格式..我的逻辑不起作用,因为我正在用not运算符更新状态。我尝试使用componentWillMount()更新值,但这也无法正常工作。任何帮助将不胜感激。以下是我的代码:-
import React from 'react'
import { Container, Segment, Icon, Form, TextArea, Button } from 'semantic-ui-react'
import './App.css'
import PrettyPrint from './PrettyPrint'
import JSON_Text from './Json_Template_Text'
import './Button.scss'
import Upload from './Upload'
import Failure from './Failure'
class jsonText extends React.Component{
state = {
text: '',
flag_button: false,
flag_fail : false
}
onChangeHandler = (event) => {
this.setState({ text : event.target.value })
}
onSubmitHandler = () => {
const json = this.state.text;
if(this.IsJsonString(json))
this.setState({ flag_button : !this.state.flag_button })
else
this.setState({ flag_fail : !this.state.flag_fail })
}
IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
render(){
return(
<Container style = {content}>
<Segment style = {segment}>
<div style = {info}>
<div><Icon name = "lightbulb" size = "large" style = {icon} /></div>
<div style = {info_div} ><p style = {text}><strong>You may be wondering what is the format of the JSON !! <br />Well, we have got you covered..</strong></p></div>
</div>
<center>
<div className = "json_example">
<PrettyPrint data = {JSON_Text} />
</div>
<div id="blank"></div>
<div id="blank"></div>
<div><p style = {text}><strong>Validate Your JSON Here..</strong></p></div>
<div id="blank"></div>
<Form onSubmit = {this.onSubmitHandler}>
<div className = "json_example" style = {form}>
<TextArea style={ TextCover } onBlur = {this.onChangeHandler} />
</div>
<div id="blank"></div><div id="blank"></div><div id="blank"></div><div id="blank"></div>
<Button className="button">
Submit
<div className="button__horizontal"></div>
<div className="button__vertical"></div>
</Button>
{this.state.flag_button && <Upload />}
{this.state.flag_fail && <Failure />}
</Form>
</center>
</Segment>
</Container>
)
}
}
export default jsonText;
不需要您使用componentWillMount
。另外该API在最新的react版本中已弃用
更新状态时,您需要直接设置flag_fail
和flag_button
状态,而不能像下面那样切换它们
onSubmitHandler = () => {
const json = this.state.text;
if(this.IsJsonString(json))
this.setState({ flag_button : true, flag_fail: false })
else
this.setState({ flag_fail : true, flag_button: false })
}