慕碼人2483693
2022-10-21 09:36:23
我有一個(gè)包含輸入的App組件。每次我輸入輸入時(shí),輸入的值都會更新,并且消息組件會根據(jù)輸入的長度打印不同的消息。同時(shí),名為Character的第三個(gè)組件將字符串的每個(gè)字母單獨(dú)打印到屏幕上。期望的行為是,當(dāng)我單擊其中一個(gè)字母時(shí),它會從字符串中刪除,新字符串會顯示在屏幕上,并且輸入也會使用新字符串進(jìn)行更新。我使用了一些 console.logs 進(jìn)行調(diào)試,一切似乎都按預(yù)期進(jìn)行,直到我嘗試更新狀態(tài)的最后一步,但由于某種原因,它沒有得到更新。class App extends React.Component { constructor(props) { super(props); this.state = { text: "" }; } render() { const handleUpdateText = event => { this.setState({ text: event.target.value }); }; const inputLength = this.state.text.length; const toArray = this.state.text.split(""); const handleDeleteLetter = index => { toArray.splice(index, 1); console.log(toArray); const updatedArray = toArray.join(""); console.log(updatedArray); this.setState({ text: updatedArray }); console.log(this.state.text); }; return ( <> <input type="text" onChange={handleUpdateText} /> <Message inputLength={inputLength} /> {toArray.map((letter, index) => ( <Character key={index} theLetter={letter} deleteLetter={() => handleDeleteLetter(index)} /> ))} </> ); }}class Message extends React.Component { render() { const { inputLength } = this.props; let codeToPrint = "The text is long enough!"; if (inputLength <= 5) { codeToPrint = "The text is not long enough!"; } return <p>{codeToPrint}</p>; }}class Character extends React.Component { render() { const { theLetter, deleteLetter } = this.props; return ( <div style={{ display: "inline-block", padding: "16px", textAlign: "center", margin: "16px", backgroundColor: "tomato" }} onClick={deleteLetter} > {theLetter} </div> ); }}完整的代碼在這里:https://codesandbox.io/s/react-the-complete-guide-assignment-2-list-conditionals-e6ty6?file=/src/App.js:51-1007我真的不明白我做錯(cuò)了什么,我覺得與生命周期方法有某種關(guān)系。任何答案都會有所幫助。謝謝你。
1 回答

ibeautiful
TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
狀態(tài)正在更新,您只需將valueprop 傳遞給輸入,以便輸入的值可以與您的狀態(tài)同步
<input type="text" value={this.state.text} onChange={handleUpdateText} />
而且您在設(shè)置后看不到更新的狀態(tài),因?yàn)樗黶etState是異步的。這就是為什么緊跟在console語句之后的setState語句顯示前一個(gè)值的原因。
此外,您應(yīng)該將函數(shù)移出渲染方法,因?yàn)槊看文慕M件重新渲染時(shí),都會創(chuàng)建新函數(shù)。您可以將它們聲明為類屬性并傳遞它們的引用
handleUpdateText = event => {
this.setState({
text: event.target.value
});
};
render() {
.......
return (
<>
<input type="text" onChange={this.handleUpdateText} />
添加回答
舉報(bào)
0/150
提交
取消