我有一個包含輸入的App組件。每次我輸入輸入時,輸入的值都會更新,并且消息組件會根據輸入的長度打印不同的消息。同時,名為Character的第三個組件將字符串的每個字母單獨打印到屏幕上。期望的行為是,當我單擊其中一個字母時,它會從字符串中刪除,新字符串會顯示在屏幕上,并且輸入也會使用新字符串進行更新。我使用了一些 console.logs 進行調試,一切似乎都按預期進行,直到我嘗試更新狀態的最后一步,但由于某種原因,它沒有得到更新。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我真的不明白我做錯了什么,我覺得與生命周期方法有某種關系。任何答案都會有所幫助。謝謝你。
React - 即使屏幕上打印的消息發生更改,類組件中的狀態也不會更新
慕碼人2483693
2022-10-21 09:36:23