我正在尝试从json服务器获取数据,并使用在输入字段中输入的值对其进行验证。 如果获取的数据和输入数据相同,则需要在字段和描述文本之间添加一个div。 我也已经创建了该组件,我认为还可以。
我已经设置了onChangeHandler,但是OnClickHandler并没有完成输入和相关json字段之间的验证。 也许我需要使用循环进行验证?
import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import styled from 'styled-components';
import ApplyButton from '../ApplyButton/ApplyButton';
import axios from 'axios';
import IsApplied from '../IsApplied/IsApplied';
const NumberContainer = styled.div`
margin-top: 10px;
`;
export default class NumberBox extends Component {
constructor(props) {
super(props);
this.state = {
giftcards: [],
first: '',
second: '',
isSeen: false
};
this.onClickHandler = this.onClickHandler.bind(this);
this.onHandleChange = this.onHandleChange.bind(this);
}
onHandleChange (property) {
return e => {
this.setState({
[property]: e.target.value
});
};
}
async componentDidMount() {
const response = await axios.get('http://localhost:3001/giftcards')
const giftcards = response.data
this.setState({giftcards: giftcards})
}
onClickHandler() {
if (this.state.first === this.state.giftcards.cardnumber &&
this.state.second === this.state.giftcards.control) {
return alert("correct") & this.setState({isSeen:true})
} else if (this.state.first.length === 0 &&
this.state.second.length === 0) {
return alert("error")
} else {
return alert("enter correct number") & console.log(this.state.giftcards)
}
}
render() {
let resultsbox;
if (this.state.isSeen) {
resultsbox = <IsApplied cardno={this.state.first}/>;
} else {
resultsbox = null;
}
return (
<NumberContainer>
{resultsbox}
<TextField
style={{ margin: 8, width: 430 }}
margin="normal"
variant="outlined"
type="search"
label="Gift Card Number"
value={this.state.first}
name="cardNomber"
onChange={this.onHandleChange('first')}
/>
<TextField
style={{ margin: 8, width: 200}}
margin="normal"
variant="outlined"
type="search"
label="Control Code"
value={this.state.second}
name="controlCoder"
onChange={this.onHandleChange('second')}
/>
<ApplyButton handle={this.onClickHandler}/>
</NumberContainer>
)
}
}
{
"giftcards": [
{
"cardnumber": "5078282848878291861",
"control": "175"
},
{
"cardnumber": "6435047555924007105",
"control": "201"
}
]
}
在使用console.log检查时,我对this.state.giftcards.cardnumber和this.state.giftcards.control的定义未定义
答案 0 :(得分:0)
this.setState({giftcards: giftcards}).
您正在将giftcards
的状态值设置为等于对象。该JSON对象具有一个礼品卡密钥。因此,onClickHandler
中的条件至少必须类似于:
if(this.state.first === this.state.giftcards.giftcards[index]){
....
}
由于关键的礼品卡具有用于其值的数组,因此您还必须像这样来决定要检查数组中的哪个项目。state.giftcards.giftcards[0] .cardnumber ...
但是,听起来更像是您只想过滤一些数据以确定用户是否输入了与卡完全相同的信息。
我们可以使用array.filter()
返回与您的用户输入匹配的任何礼品卡。如果有的话,我们将isSeen设置为true。尝试对onClickHandler()
做这样的事情:
onClickHandler(){
const { giftcards, first, second } = this.state
const matchingGiftCards = giftcards.filter((card) => {
return card.cardnumber == first && card.control == second
})
//if there are any matching giftcards we will set isSeen to tru
if(matchingGiftCards.length > 0){
this.setState({isSeen:true})
}
}