Javascript 由于useRef,React useState未更新
我的react代码遇到了一个非常奇怪的问题:useState没有更新视图,在尝试了所有操作之后,问题仍然存在。我编写了一个简单的代码来解释这个问题:Javascript 由于useRef,React useState未更新,javascript,reactjs,use-effect,use-state,use-ref,Javascript,Reactjs,Use Effect,Use State,Use Ref,我的react代码遇到了一个非常奇怪的问题:useState没有更新视图,在尝试了所有操作之后,问题仍然存在。我编写了一个简单的代码来解释这个问题: function(){ const[enterJob,setEnterJob]=useState(false); const[jobSelection,setJobSelection]=useState(数组(someList.length).fill(false)); const jobRef=useRef(); const handleJob
function(){
const[enterJob,setEnterJob]=useState(false);
const[jobSelection,setJobSelection]=useState(数组(someList.length).fill(false));
const jobRef=useRef();
const handleJobClick=i=>{
const n=parseInt(i.target.id.charAt(0));//列表足够小,允许这样做
设c=工作选择;
c[n]=!c[n];
职业选择(c);
};
康斯特酒店=(e)=>{
如果(!jobRef.current.contains(如目标)){
setEnterJob(假);
};
};
useffect(()=>{
窗口。addEventListener(“鼠标向下”,把手);
return()=>window.removeEventListener(“mousedown”,handleMouse);
});
返回(
setEnterJob(真)}/>
{someList.map((项,索引)=>
- {jobSelection[index]?项:“您单击了按钮”}
)}
)
}
问题在于,您正在更改您的作业选择
,而不是创建新对象。如果对象具有与以前相同的引用,react将跳过重新渲染器:
const handleJobClick = i => {
const n = parseInt(i.target.id.charAt(0)); // the list is small enough to allow this
let c = [...jobSelection]; // Create a new array
c[n] = !c[n];
setJobSelection(c);
};
问题
如果我理解你的问题,那么我相信这是因为你正在直接改变你的状态
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]; // <-- mutation!
setJobSelection(c);
};
太好了,非常感谢,就这样!我需要学习更多关于突变的知识。太好了!非常感谢,就这样@Domino987的解决方案简单一点,但这个更容易理解。没问题,对象、数组甚至字符串和布尔值也是如此。如果你有任何问题,打电话给我up@CharbelImad当然可以我注意到了一些其他问题,所以我更新了我的答案以帮助解决这些问题。感谢您的更正。当以这种方式传递索引值@drew reese时,我遇到了一个奇怪的问题:我得到了一个无限循环渲染错误。我会更仔细地看一看,然后再打给你。@CharbelImad你是否更改了
handleJobClick
函数签名<代码>handleJobClick=index=>()=>{…}?它是一个curried函数,用于获取索引并返回用作回调的函数,也就是说,它接受事件,但由于我们不关心事件对象中的任何内容,因此不需要为其分配标识符。
const handleJobClick = index => () => {
setJobSelection(jobSelection => jobSelection.map(
(selection, i) => index === i ? !selection : selection // <-- toggle selection at matched index
);
};
...
<ul>
{someList.map((item, index)=> (
<li
key={index} // <-- index as react key, ok since not adding/removing/sorting jobs
onClick={handleJobClick(index)} // <-- pass index to handler
>
{jobSelection[index] ? item : "you clicked on the button"}
</li>
))}
</ul>