简体   繁体   English

反应如何使用带有 Map 值的 setState

[英]React how to use setState with Map value

I'm at a loss here.我在这里不知所措。 Here is the relevant code I have:这是我拥有的相关代码:

const TraitModal = (props) => {
const [abiltiesChecked, setAbiltiesChecked] = React.useState(new Map());
const handleAbilitiesCheck = (e) => {
        var newabilitiesCH=abiltiesChecked.set(e.target.id, e.target.checked);
        setAbiltiesChecked(newabilitiesCH);
    };
return(
<Form>
GetAbilities().map((a) => (
                                        <div key={`custom-${a}-2`}>
                                            <Form.Check
                                                custom
                                                checked={!!abiltiesChecked.get(`abilities-${a}`)}
                                                type="checkbox"
                                                id={`abilities-${a}`}
                                                label={`${a}`}
                                                onChange={handleAbilitiesCheck.bind(this)}
                                            />
                                        </div>
                                    ))}
</Form>
    );
    }


In my understanding the setAbiltiesChecked(newabilitiesCH) replaces the old abiltiesChecked and thus would cause the React component to rerender, however that's not whats happening at all.据我了解, setAbiltiesChecked(newabilitiesCH) 替换了旧的 abiltiesChecked ,因此会导致 React 组件重新呈现,但这根本不是发生的事情。 The state does get updated as I figured out with some console logs, but it does not get updated from handleAbilitiesCheck function. state 确实得到了更新,因为我发现了一些控制台日志,但它没有从 handleAbilitiesCheck function 中更新。

I have another function that basically rerenders on a input into a text box and that triggers a rerendering of the checkboxes, but I need them to show that the checkbox was actually clicked, whats the error with my code?我有另一个 function 基本上在输入到文本框时重新呈现并触发复选框的重新呈现,但我需要它们显示复选框实际上已被单击,我的代码有什么错误?

Your problem is that you're mutating your stateful object (your call to state changes the current map object), then assigning to it.您的问题是您正在改变有状态的 object (您对 state 的调用会更改当前的 map 对象),然后分配给它。 React performs a diff on the object, sees no change, and therefore does not re-render. React 在 object 上执行差异,看不到任何变化,因此不会重新渲染。

In this specific case, replace:在这种特定情况下,替换:

    var newabilitiesCH=abiltiesChecked.set(e.target.id, e.target.checked);

with

    var newabilitiesCH= new Map(abiltiesChecked).set(e.target.id, e.target.checked);

The new copy should be recognized by React as a new state. React 应该将新副本识别为新的 state。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM