【问题标题】:ReactJS Update or Remove item in arrayListReactJS 更新或删除 arrayList 中的项目
【发布时间】:2020-05-14 07:27:37
【问题描述】:

这个问题可能会落下。我有一个map() 函数,数据来自API。当某些事情发生变化时,我需要在不刷新页面的情况下更改地图中的项目。我正在使用 findIndex。但有些理由是错误的。 现在我有这样的代码:

const handleSubmit = values => {
    api.putItem(`users/${data.id}`, params)
    .then(res => {
        modelClose();
        console.log(res);
        let response = res.data;
        let index = userForeignInfo.findIndex(response.id);
        userForeignInfo.splice(index, 1, response);
        setLoadingBtn(false);
    }).catch(e => {
        console.log(e.toString());
        setLoadingBtn(false);
    })
};

我的userForeignInfo函数如下:

const [userForeignInfo, setuserForeignInfo] = useState([]);
{userForeignInfo.map((item, index) =>
    (
       <li key={item.id} onClick={() => handlePassInfoShow(item)}>
            {index + 1} {item.first_name} {item.last_name}
       </li>
     )
   )}

返回错误如下。

TypeError: 7 is not a function

现在通过api.put() 方法保存数据。但是,数组的状态会在页面重新加载后更新。我需要在不重新加载页面的情况下更改数组中的项目。 我哪里错了?

【问题讨论】:

  • 你知道哪一行抛出了 TypeError 吗?它应该在控制台输出中

标签: javascript reactjs arraylist


【解决方案1】:

您修改了变量userForeignInfo,但没有使用setuserForeignInfo。所以你的组件不会被更新。

试试这样的:

const handleSubmit = data => {  // rename "values" by "data" here
    api.putItem(`users/${data.id}`, params)  // params is not defined in your code.
    .then(res => {
        modelClose();
        console.log(res);
        let response = res.data;
        const newUserForeignInfo = [...userForeignInfo]; // Copy your array here before using splice
        let index = newUserForeignInfo.findIndex(response.id);
        newUserForeignInfo.splice(index, 1, response);
        setuserForeignInfo(newUserForeignInfo); // Update the state here
        setLoadingBtn(false);
    }).catch(e => {
        console.log(e.toString());
        setLoadingBtn(false);
    })
};

【讨论】:

  • 谢谢博尔,但没有任何改变。
  • 你建议的选项不起作用,还是同样的错误。
  • 好吧,我只是复制/粘贴您的代码,但有一些错误。检查您的handleSubmit 参数。 values 未使用。也许您应该将其重命名为 dataparams 也没有定义。
猜你喜欢
  • 1970-01-01
  • 2021-12-08
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多