watch vs useState in React



我开始学习React。在wytsx文件中,我有一个函数,里面有一个useState方法来监视一些值。还有一种watch方法来观察其他值。

React中的手表和useState有什么区别?我的意思是,假设我必须观察文本框或组合框中的值,并对其变化做出反应。我应该使用什么方法,watch还是useState

这是沙盒StackBlitz

import * as React from 'react';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import './style.css';
export default function App() {
const { watch } = useForm({ mode: 'all', reValidateMode: 'onBlur' });
// this ?
const [city, setCity] = useState<string>('Moscow');
// or this ?
const wcity = watch('city');
return (
<div>
<p>Start editing & look at the console how values changes :</p>
{/* is there a way to watch city changes witout onChange in input:? */}
<input value={wcity} defaultValue="any" /> <br />
<label>{wcity}</label>
</div>
);
}

我应该如何使用watchuseState来记录city的更改(如果可能,请使用onChange方法(?

在您提供的沙箱中输入时,我既看不到<label>也看不到控制台上的更改,我查看了watch的文档,这里是有效的更新版本:

import * as React from 'react';
import { useForm } from 'react-hook-form';
import './style.css';
export default function App() {
const { watch, register } = useForm({
mode: 'all',
reValidateMode: 'onBlur',
});
// Will console the changes
React.useEffect(() => {
const subscription = watch((value, { name, type }) =>
console.log(value, name, type)
);
return () => subscription.unsubscribe();
}, [watch]);
const wcity = watch('city', 'any'); // watch input tag registered with 'city' and put default value of wcity as 'any'
return (
<div>
<p>Start editing & look at the console how values changes :</p>
<input value={wcity} {...register('city')} /> <br />
<label>{wcity}</label>
</div>
);
}

正如您所看到的,标记中缺少对register()的调用,如果您想控制台更改,则需要按照文档中的描述编写useEffect

最后,如果你想在不使用任何第三方库的情况下实现这一点,那么你可以这样做:

import * as React from 'react';
import { useState } from 'react';
import './style.css';
export default function App() {
const [city, setCity] = useState<string>('any'); // default value for 'city' state is 'any'
const cityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.value);
setCity(e.target.value);
};
return (
<div>
<p>Start editing & look at the console how values changes :</p>
<input value={city} onChange={cityChange} /> <br />
<label>{city}</label>
</div>
);
}

watch:的Kartoos答案的一个变体

import * as React from 'react';
import { useForm } from 'react-hook-form';
export default function App() {
const { register, watch } = useForm({ mode: 'all', reValidateMode: 'onChange' });
const cityValue = watch('city', 'any');
React.useEffect(()=>{
console.log('cityValue changed:', cityValue)
}, [cityValue])
return (
<div>
<p>Start editing & look at the console how values changes :</p>      
<input name='city' defaultValue={cityValue} {...register('city')}/> <br />
<label>{cityValue}</label>
</div>
);
}

最新更新