有一个组件通过存储在状态中的数组进行映射。一个按钮,当它被点击的时候,它会更新状态,这个动作是有效的。
问题是组件没有更新。
以下是代码:
const MyComponent = () => {
   ...
   const [fields, setFields] = useState([{value: 'test', editable: false},
                                         {value: 'test2', editable: false}]);
  ...
  const toggleClass = (id) => {
     const aux = fields;
     aux[id].editable = true;
     setFields(aux);
  }
  ...
  return (
     <div>
      ...
      {fields.map((field, id) => {
          return (
            <div>
              <input className={field.editable ? 'class1' : 'class2'} />
              <button onClick={() => toggleClass(id)}>click</button>
            </div>
          );
      })}
     </div>
  );我放置日志,状态(fields)在单击可编辑= true后被更新。但是css类并没有改变。
这个问题有什么解决办法吗?
发布于 2021-06-09 11:16:03
您需要复制现有的状态数组,否则就会发生变异状态,这是一种错误的做法。
const toggleClass = id => {
  const aux = [...fields]; //here we spread in order to take a copy
  aux[id].editable = true; //mutate the copy
  setFields(aux); //set the copy as the new state
};发布于 2021-06-09 11:36:04
之所以会发生这种情况,是因为您正在改变fields的值,这使得它无法确定是否更新组件。理想情况下,如果您应该向setFields提供一个新对象的话。因此,您的toggleClass函数应该如下所示:
const toggleClass = (id) => {
const aux = [...fields]; //This gives a new array as a copy of fields state
aux[id].editable = !aux[id].editable;
setFields(aux);}
顺便说一句,我还注意到,您没有为映射输出的每个key分配一个div支柱。提供key支持是一个很好的实践,并且最好不要使用索引作为关键。
https://stackoverflow.com/questions/67902985
复制相似问题