Function render after splice and setState()

懵懂的女人 提交于 2020-01-22 03:22:24

问题


I want my React function to re-render after I splice an array.

Here Is (part of) the function (using Hooks):

function showProblem() {
  const [andArray, setAndArray] = useState([]);

const deleteTag = (i, arr) => {
    let and = andArray;
    switch (arr) {
      case "and":
        and.splice(i, 1);
        setAndArray(and);
        break;
      default:
        return null;
    }
  };


return(
<div>
    {andArray.map((and, i) => {
            return (
              <span
                onClick={() => deleteTag(i, "and")}
                key={i}
              >
                {and}
              </span>
            );
     })}
</div>
)
}

When I click on the SPAN element, I want my "andArray.map" to render again.

The splice is working correctly, my array is ok... but the function does not re-render.

Thanks a lot.


回答1:


.splice mutates the array. React states have to be immutable. The immuatble way would be:

  setAndState(and.filter((_, i2) => i2 !== i));


来源:https://stackoverflow.com/questions/56039001/function-render-after-splice-and-setstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!