我的反应代码遇到了一个非常奇怪的问题:useState 没有更新视图,并且在尝试了所有操作之后,问题仍然存在。我做了一个简单的代码来解释这个问题:
function(){
const [enterJob, setEnterJob] = useState(false);
const [jobSelection, setJobSelection] = useState(Array(someList.length).fill(false));
const jobRef = useRef();
const handleJobClick = i => {
const n = parseInt(i.target.id.charAt(0)); // the list is small enough to allow this
let c = jobSelection;
c[n] = !c[n];
setJobSelection(c);
};
const handleMouse = (e) =>{
if (!jobRef.current.contains(e.target)){
setEnterJob(false);
};
};
useEffect(() => {
window.addEventListener("mousedown", handleMouse);
return () => window.removeEventListener("mousedown", handleMouse);
});
return(
<div ref={jobRef}>
<input onFocus={()=> setEnterJob(true)} />
<div style={{display: `${enterJob ? 'flex' : 'none'}`}} >
<ul>
{ someList.map((item,index)=>
<li id={`${index}`} onClick={handleJobClick}> {jobSelection[index] ? item : "you clicked on the button"} </li> )}
</ul>
</div>
</div>
)
}
一些解释:我正在使用 UseEffect 和 useRef 创建一个下拉菜单,当您在容器外单击时它会消失。现在,当我想单击此下拉菜单的值时,它不会更新 DOM,而我正在使用 useState 更新负责更改的字符串的值。
提前谢谢你,查贝尔