我是 Stack Overflow 和 React 的新手,需要一些幫助。
我開始了一個學習 React JS 的小專案。在這個專案中,我可以輸入一個文本,這個文本將被顯示但經過哈希處理(哈希函式是自制的,只是一個模擬)。一切正常,只是它不會在倒數第二行(<div{ hashedText }/div>)顯示文本。好像我必須更新它,但我不知道如何。任何提示?
code
從“反應”匯入反應從“反應”匯入{useState}
const TextInput = () => {
let hashedText = ""
const [text, setText] = useState('')
const getInput = (string) => {
setText(string)
hashedText = hash(string)
console.log('this works')
}
// Hasher
const hash = (string) => {
console.log('you made it')
//set variable hash as 0
var hash = 0;
// if the length of the string is 0, return 0
if (string.length === 0) return hash;
for (let i = 0 ;i<string.length ; i ) {
let ch = string.charCodeAt(i);
hash = ((hash << 5) - hash) ch;
hash = hash & hash;
}
return hash
}
return (
<div className='form-control'>
<h1>Hasher</h1>
<label>Text</label>
<input onInput={e=> getInput(e.target.value)}
type='text'
placeholder='Enter Informations'></input>
<label>Hash</label>
<div>{ hashedText }</div>
</div>
)
}
匯出默認文本輸入
uj5u.com熱心網友回復:
僅當state或props更改時,React 才會重新呈現組件的 html 。所以我建議將 保留hashedText在本地狀態。
uj5u.com熱心網友回復:
由于您的區域變數,問題會出現hashedText。當您更新狀態或由于其他一些鉤子等原因時,組件會重新渲染useEffect。在這種情況下,即使您觸發了useState鉤子,也不會在text任何地方讀取狀態變數。React 優化了 cod 以嘗試盡可能少地重新渲染,因為text沒有使用 - 它不會更新任何內容,包括您的hashedText.
為了解決這個問題,你需要將你的散列變數存盤在一個狀態中,或者讀取它,然后將它散列到狀態本身,而不是將 props 傳遞給方法。
可以這樣做來存盤散列
const getInput = (string) => {
setText(hash(string));
};
或者使用useEffect鉤子
const [hashedText, setHashedText] = useState("");
const [text, setText] = useState("");
const getInput = (string) => {
setText(string);
};
useEffect(() => {
setHashedText(hash(text));
}, [text]);
此外,建議在onChange={(e) => getInput(e.target.value)}, 上使用<input>, 而不是onInputAND 不要使用varbut 代替letand const。所以而不是var hash = 0;=> let hash = 0;。var舊且不安全。由于您使用的是es6JS - 您應該堅持使用es6標準而不是添加舊版本
uj5u.com熱心網友回復:
您可以使用onChange事件(或不使用),input是自閉標簽
const getInput = v => {
setText(hash(v))
};
<input
onChange={e=> getInput(e.target.value)}
type='text'
placeholder='Enter Informations'
/>
<label>{text}</label>
uj5u.com熱心網友回復:
問題是您不存盤 hashedText 的狀態。當組件安裝或更新時,您只需將空字串作為值分配給它。試試下面的代碼。
function TextInput() {
const [hashedText, setHashedText] = useState('');
const [text, setText] = useState('')
function getInput(string) {
setText(string)
setHashedText(hash(string))
console.log('this works')
}
// Hasher
function hash(string) {
console.log('you made it')
//set variable hash as 0
var hash = 0;
// if the length of the string is 0, return 0
if (string.length === 0) return hash;
for (let i = 0 ;i<string.length ; i ) {
let ch = string.charCodeAt(i);
hash = ((hash << 5) - hash) ch;
hash = hash & hash;
}
return hash
}
return (
<div className='form-control'>
<h1>Hasher</h1>
<label>Text</label>
<input onInput={e=> getInput(e.target.value)}
type='text'
placeholder='Enter Informations'></input>
<label>Hash</label>
<div>{hashedText}</div>
</div>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/323458.html
標籤:反应
上一篇:我想在反應陣列中添加一個物件
