我在使用函数组件时遇到问题。我正在编写 Hangman 游戏,但在尝试让员工了解字母发现时遇到了困难。这是我的代码。
App.js
import CreateSubject from './components/CreateSubject'
import Hangman from './components/Hangman'
import { HangmanProvider } from './context/HangmanContext'
function App() {
return (
<HangmanProvider>
<div className="App">
<CreateSubject/>
<Hangman/>
</div>
</HangmanProvider>
);
}
export default App;
CreateSubject.js
import {HangmanContext } from '../context/HangmanContext'
function CreateSubject(props){
const {password,displayGame,displayForm} = useContext(HangmanContext)
const [subject,setSubject] = password
const [gameDisplay,setGameDisplay] = displayGame
const [createSubjectDisplay,setCreateSubjectDisplay] = displayForm
const handleSubmit = (e) =>{
e.preventDefault()
if(subject != ''){
setCreateSubjectDisplay('none')
setGameDisplay('')
}
}
const handleChange = (e) =>{
setSubject(e.target.value)
e.target.value = subject
}
return(
<form style={{display: createSubjectDisplay}} onSubmit={handleSubmit}>
<label>
<div>Enter a Word:</div>
<input type='text'
value={subject}
onChange={handleChange}
className='createSubject'
maxLength='40'/>
</label>
<button type='submit'>Create</button>
</form>
)
}
export default CreateSubject
Hangman.js
import al from '../alphabet'
import {HangmanContext} from '../context/HangmanContext'
const Hangman = (props) =>{
const {password,displayGame,displayForm} = useContext(HangmanContext)
const [subject,setSubject] = password
const [gameDisplay,setGameDisplay] = displayGame
const [createSubjectDisplay,setCreateSubjectDisplay] = displayForm
let passwordArr = Array.from(subject)
const [hiddenPassword,changeHiddenPassword] = useState()
useEffect(() => {
let passwordArr = Array.from(subject)
changeHiddenPassword(passwordArr.map(item => '_'))
},[]);
const chooseLetter = (e) => {
let letter = e.target.innerHTML
passwordArr.forEach((e,i) => {
if (e == letter){
console.log(hiddenPassword)
}
})
}
const letters = al.map((letter) =>
<span onClick={chooseLetter}>{letter}</span>
)
return(
<div style={{display:gameDisplay}}>
<div className='password'>
{
//passwordArr.map((item,i) => <span>{hiddenPasswordArr[i]}</span>)
}
</div>
<div className='wrapper'>
<div className='pass_input'>Enter password:<input type='text' maxLength='30'/></div>
<div className='alphabet'> {letters} </div>
</div>
</div>
)
}
export default Hangman
我的问题是在 Hangman.js 中,当我尝试更改数组的“隐藏密码”状态时。当我在控制台中输出此状态时,它会显示一个空数组。我做错了什么?
答案 0 :(得分:0)
您需要初始化您的 hiddenPassword
状态:
const [hiddenPassword,changeHiddenPassword] = useState(passwordArr.map(item => '_'))
答案 1 :(得分:0)
subject
可能必须在 useEffect
的依赖项数组中
useEffect(() => {
let passwordArr = Array.from(subject)
changeHiddenPassword(passwordArr.map(item => '_'))
},[subject]);