我是React的新手,并尝试使用一个API进行简单的登录。连接工作正常,所以我想在登录失败时创建一个div。
例如,警报(“ NOT LOGIN”)后出现一个div“错误的用户名或密码”
我阅读了stackoverflow并做出了反应,但是我有疑问,因为我想在渲染器之外操纵DOM。
例如此代码:
render() {
var renderedOutput = arr.map(item => <div> {item} </div>)
return (
<div>
{renderedOutput}
</div>
);
}
像这样的变种。也许是一个非常初学者的错误,但是我陷入了困境。感谢您的帮助,对不起您的问题。
import *;
class App extends Component {
handleSubmit = e => {
e.preventDefault();
const user = {
usuario: this.usuario.value,
contraseña: this.password.value
};
axios.post(`http://api`, user).then(res => {
this.setState({
data: res.data,
loading: true
});
if (Object.keys(res.data).length > 0) {
alert("LOGIN");
} else {
alert("NOT LOGIN");
}
console.log(res.data);
});
}
render() {
return (
<Container>
<Form onSubmit={this.handleSubmit}>
<Row>
<Col md="4"> </Col>{" "}
<Col md="4">
<Card>
<CardBody>
<FormGroup>
<InputGroup>
<InputGroupAddon addonType="append">
<InputGroupText>
<FontAwesomeIcon icon={faUser} />{" "}
</InputGroupText>{" "}
</InputGroupAddon>{" "}
<Input
placeholder="Usuario"
type="text"
innerRef={element => {
this.usuario = element;
}}
/>{" "}
</InputGroup>{" "}
</FormGroup>
<FormGroup>
<InputGroup>
<InputGroupAddon addonType="append">
<InputGroupText>
<FontAwesomeIcon icon={faKey} />{" "}
</InputGroupText>{" "}
</InputGroupAddon>{" "}
<Input
placeholder="Password"
type="password"
innerRef={element => {
this.password = element;
}}
/>{" "}
</InputGroup>{" "}
</FormGroup>
<Row>
<Col md="8"> </Col>{" "}
<Col md="4">
<Button color="success"> Login </Button>{" "}
</Col>{" "}
</Row>{" "}
</CardBody>{" "}
</Card>{" "}
</Col>{" "}
<Col md="4"> </Col>{" "}
</Row>{" "}
</Form>
</Container>
);
}
}
export default App;
答案 0 :(得分:1)
您需要在检测到api故障时将错误信息设置为状态,然后在render函数中(如果发现错误状态)可以相应地呈现错误消息html。我们可以在返回jsx之前在render中编写任何javascript。
import *;
class App extends Component {
state={
data: null,
loading: false,
errorMessage: ''
}
handleSubmit = e => {
e.preventDefault();
const user = {
usuario: this.usuario.value,
contraseña: this.password.value
};
axios.post(`http://api`, user).then(res => {
this.setState({
data: res.data,
loading: true
});
if (Object.keys(res.data).length > 0) {
alert("LOGIN");
this.setState({
errorMessage: ''
});
} else {
this.setState({
errorMessage: 'Bad Login details'
});
alert("NOT LOGIN");
}
console.log(res.data);
});
}
render() {
let errorMessageHtml;
if(this.state.errorMessage){
errorMessageHtml = <p>{this.state.errorMessage}</p>
}
return (
<Container>
<Form onSubmit={this.handleSubmit}>
<Row>
<Col md="4"> </Col>{" "}
<Col md="4">
<Card>
<CardBody>
<FormGroup>
<InputGroup>
<InputGroupAddon addonType="append">
<InputGroupText>
<FontAwesomeIcon icon={faUser} />{" "}
</InputGroupText>{" "}
</InputGroupAddon>{" "}
<Input
placeholder="Usuario"
type="text"
innerRef={element => {
this.usuario = element;
}}
/>{" "}
</InputGroup>{" "}
</FormGroup>
<FormGroup>
<InputGroup>
<InputGroupAddon addonType="append">
<InputGroupText>
<FontAwesomeIcon icon={faKey} />{" "}
</InputGroupText>{" "}
</InputGroupAddon>{" "}
<Input
placeholder="Password"
type="password"
innerRef={element => {
this.password = element;
}}
/>{" "}
</InputGroup>{" "}
</FormGroup>
<Row>
<Col md="8"> </Col>{" "}
<Col md="4">
<Button color="success"> Login </Button>{" "}
</Col>{" "}
</Row>{" "}
</CardBody>{" "}
</Card>{" "}
</Col>{" "}
<Col md="4"> </Col>{" "}
</Row>{" "}
{errorMessageHtml}
</Form>
</Container>
);
}
}
export default App;
答案 1 :(得分:1)
对于这种类型的问题,您不必进行任何手动的DOM操作。完成此操作的“正确”方法是在异步请求完成后更新状态(setState
),这将触发重新渲染。如果请求失败,则可以存储错误,如果请求成功,则可以清除错误(成功登录后,您也可能会离开此页面,但这不在范围内)。
这是一个简单的工作示例,应演示如何有条件地呈现错误。 (由于这是一个示例,因此在表格中输入内容无关紧要-单击“提交”以发出将进行404并以错误更新状态的请求。)
class Example extends React.Component {
constructor (props) {
super(props)
this.state = {errors: []}
}
setErrors = (...errors) => {
this.setState({errors})
}
submitForm = () => {
// intentionally return a 404 as an example
// change to false to mock a valid ajax request
const hasError = true
axios.get(`https://jsonplaceholder.typicode.com/${
hasError ? 'fake' : 'todos/1'}`)
.then(() => {
this.setErrors()
})
.catch(() => {
this.setErrors('Invalid Email Or Password')
})
}
render () {
return (
<div>
<div style={{color: 'red'}}>
{this.state.errors.map(e => <div>{e}</div>)}
</div>
<div><label>Email<input type="email" /></label></div>
<div><label>Password<input type="password" /></label></div>
<button type="button" onClick={this.submitForm}>Submit</button>
</div>
)
}
}
ReactDOM.render(<Example />, document.querySelector('#app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<div id="app"></div>