splice 和 setState() 后的函数渲染 [英] Function render after splice and setState()

查看:60
本文介绍了splice 和 setState() 后的函数渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 React 函数在拼接数组后重新渲染.

这是(部分)函数(使用 Hooks):

function showProblem() {const [andArray, setAndArray] = useState([]);const deleteTag = (i, arr) =>{让和 = andArray;开关(arr){案例和":and.splice(i, 1);setAndArray(and);休息;默认:返回空;}};返回(<div>{andArray.map((and, i) => {返回 (<跨度onClick={() =>deleteTag(i, "and")}键={i}>{和}</span>);})}

)}

当我点击 SPAN 元素时,我希望我的andArray.map"再次呈现.

拼接工作正常,我的数组没问题...但函数没有重新渲染.

非常感谢.

解决方案

.splice 改变数组.React 状态必须是不可变的.不变的方式是:

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

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.

解决方案

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

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

这篇关于splice 和 setState() 后的函数渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆