Reactjs 反应与';t使用所有新状态重新渲染
我正在建立一个登记表,我遇到了一个问题。在用户完成字段后,我使用regex进行验证检查。每个验证函数都将设置一条错误消息。尽管我故意触发了所有这些错误,但如果我提交表单,只会出现一个错误。这是我的密码:Reactjs 反应与';t使用所有新状态重新渲染,reactjs,typescript,jsx,native,Reactjs,Typescript,Jsx,Native,我正在建立一个登记表,我遇到了一个问题。在用户完成字段后,我使用regex进行验证检查。每个验证函数都将设置一条错误消息。尽管我故意触发了所有这些错误,但如果我提交表单,只会出现一个错误。这是我的密码: function RegisterScreen(): JSX.Element{ const pwInput = React.createRef(); const [firstName, setFirstName] = useState(''); const [last
function RegisterScreen(): JSX.Element{
const pwInput = React.createRef();
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [birthday, setBirthday] = useState<Date | null>(null);
const [isSelected, setSelection] = useState(false);
const [openTerms, setOpenTerms] = useState(false);
const [emailError, setEmailError] = useState<string | null>(null);
const [passError, setPassError] = useState<string | null>(null);
const [confPassError, setConfPassError] = useState<string | null>(null);
const [isTermsChecked, setIsTermsChecked] = useState<string | null>(null);
function _validateEmail(): boolean{
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(re.test(email))
return true;
else{
setEmailError(RegisterErrors.emailError);
return false;
}
}
function _validatePw(): boolean{
const re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/
if(re.test(password)) return true;
else{
setPassError(RegisterErrors.pwWeak);
return false
}
}
function _pwMatch(): boolean{
if(password == confirmPassword){
return true;
}else{
setConfPassError(RegisterErrors.pwConfirmMatchError);
return false;
}
}
function _validateAge(): boolean{
return true;
}
function _validateTermsAndCond(): boolean{
return true;
}
function validateFieldsAndRegister(){
console.log(email);
console.log(password);
console.log(confirmPassword);
if( _validateEmail() && _validatePw() && _validateAge() && _validateTermsAndCond() && _pwMatch()){
//trimite la firebase
console.log("okay")
}else{
console.log('wrong fields')
}
}
return(
<SafeAreaView style={{flex:1}}>
<ScrollView>
<View style = {{flex:1, alignItems: "center", justifyContent:"center",backgroundColor:"white"}}>
<TermsAndConditions open = {openTerms} close = { ()=>setOpenTerms(false) }/>
<Image source={require("../../images/logoR.png")} style={styles.logoImg}/>
<Text style={styles.mainText}>Register</Text>
<Input
containerStyle={styles.inputView}
inputContainerStyle={{backgroundColor:"white"}}
placeholder="First Name..."
placeholderTextColor="rgb(0,0,0)"
errorStyle={{ color: 'red' }}
onChangeText={text => setFirstName(text)}/>
<Input
containerStyle={styles.inputView}
placeholder="Last Name..."
placeholderTextColor="rgb(0,0,0)"
errorStyle={{ color: 'red' }}
onChangeText={text => setLastName(text)}/>
<Input
onFocus={()=>{setPassError(null)}}
secureTextEntry
containerStyle={styles.inputView}
placeholder="Password..."
placeholderTextColor="rgb(0,0,0)"
errorStyle={{ color: 'red' }}
errorMessage={passError}
onChangeText={text =>setPassword(text)}/>
<Input
secureTextEntry
onFocus = {()=>{setConfPassError(null)}}
containerStyle={styles.inputView}
placeholder="Confirm Password..."
placeholderTextColor="rgb(0,0,0)"
errorStyle={{ color: 'red' }}
errorMessage={confPassError}
onChangeText={text =>setConfirmPassword(text)}/>
<Input
containerStyle={styles.inputView}
onFocus={()=>{setEmailError(null)}}
placeholder="Email..."
placeholderTextColor="rgb(0,0,0)"
errorStyle={{ color: 'red' }}
errorMessage={emailError}
onChangeText={text => setEmail(text)}/>
<View style={styles.checkboxContainer}>
<CheckBox
value={isSelected}
onValueChange={()=>{setSelection(!isSelected)}}
style={styles.checkbox}
/>
<TouchableOpacity onPress = {()=> {setOpenTerms(true);}}>
<Text style={styles.label}>Terms and Conditions</Text>
</TouchableOpacity>
</View>
<TouchableOpacity style={{...styles.inputView, ...styles.regBtnContainer}} onPress = {()=>{validateFieldsAndRegister()}}>
<Text style = {styles.txtRegBtn}>Register</Text>
</TouchableOpacity>
</View>
</ScrollView>
</SafeAreaView>
)
}
这里有一个片段说明了正在发生的一些事情。它说明了更新状态的三种不同策略 第一组将所有三个
setState()
调用组合成一个函数调用,并且不使用if()
语句检查结果。状态更改会立即显示
第二个函数将更新分成三个单独的调用async
函数,这些函数依次在调用setState()
之前等待一个超时函数。这些调用是在OP从if()
语句中执行时进行的。每个异步函数都返回一个Promise,该Promise将被评估为truthy,我们可以看到控制台上记录了“Promise”。然后,超时的结果逐渐显现出来
第三个案例最接近OP的问题。它还从if()
语句中进行单独的调用,但它们是同步的,并返回false
。第一个调用完成它的setState()
调用,返回false并停止来自if内部的进一步调用。因为状态已更改,所以React调用渲染,我们看到单个状态更改
所有这一切的结果是,最好在if()
语句之前进行验证调用,或者更好的做法是收集所有验证结果,然后将所有setState()
调用组合到一个函数中。这将允许React更有效地对这些更改进行分组,并调用尽可能少的渲染
(对于混乱的代码片段,很抱歉,内置的babel似乎无法处理async/await
)
.container{
显示器:flex;
}
.举例{
保证金:1rem;
填充:1rem;
边框:1px纯色灰色;
}
钮扣{
保证金:1rem;
}
const{useState}=React
函数App(){
const[stateOne,setStateOne]=useState(1);
const[stateTwo,setStateTwo]=useState(1);
const[statetree,setstatetree]=useState(1);
常量cycleStateSingle=()=>{
setStateOne((状态)=>状态+1);
设置状态二((状态)=>状态+1);
设置状态三((状态)=>状态+1);
}
const[stateOnePromise,setStateOnePromise]=useState(1);
const[stateTowPromise,setStateTowPromise]=useState(1);
常量[StateTreePromise,SetStateTreePromise]=使用状态(1);
const cycleOne=async()=>{
等待新的承诺(resolve=>setTimeout(resolve,1000));
setStateOnePromise((状态)=>状态+1);
}
const cycleTwo=async()=>{
等待新的承诺(resolve=>setTimeout(resolve,2000));
SetStateTowPromise((状态)=>状态+1);
}
const cycleThree=async()=>{
等待新的承诺(resolve=>setTimeout(resolve,3000));
SetStateThroPromise((状态)=>状态+1);
}
常量cycleStatePromise=()=>{
如果(cycleOne(真)和CycleWO(真)和cycleThree(真)){
console.log(“承诺”);
}
}
const[stateOneStepped,setStateOneStepped]=useState(1);
常量[StateTowStepped,SetStateTowStepped]=使用状态(1);
const[statetreestepped,setstatetreestepped]=useState(1);
const cycleonested=()=>{
SetStateonStepped((状态)=>状态+1);
返回false;
}
const cycleTwoStepped=()=>{
SetStateTowStepped((状态)=>状态+1);
返回false;
}
const cycleThreeStepped=()=>{
SetStateTreeStepped((状态)=>状态+1);
返回false;
}
const cyclestatestapped=()=>{
if(cycleonested()&&cyclethostepped()&&cycleThreeStepped()){
console.log('stepped');
}
}
返回(
状态1:{stateOne}
状态2:{stateTwo}
国家3:{statetree}
单一状态变化
国家1:{stateOnePromise}
国家2:{stateTwoPromise}
第3国:{statetreepromise}
承诺状态变更
状态1:{stateOneStepped}
状态2:{stateTwoStepped}
状态3:{statetreestepped}
阶跃状态变化
);
}
ReactDOM.render(,document.getElementById('root'));
您是否考虑过状态更新的异步性质?这可能只是一个竞争条件。看起来只要验证函数返回false,其余的就不会执行,因为这样做没有意义。。由于我使用AND运算符,因此总体结果将为false。这是typescript/javascript中的东西吗?是的,JS会短路。这是javascript的东西
export const RegisterErrors = {
emailError: "You must enter a valid email",
pwConfirmMatchError:"The passwords you entered are not the same",
termsAndCondError:"You must read and agree with the Terms and Conditions",
birthdayError:"You must be 21 or older",
pwWeak:"Your password must contain: a lowercase letter, a acapital letter, a number and minimum 8 characters"
}