【问题标题】:state undefined inside async function ( Cannot read property 'filter' of undefined ) - react js异步函数内部未定义状态(无法读取未定义的属性“过滤器”)-反应js
【发布时间】:2021-08-02 10:12:34
【问题描述】:

我的代码是直截了当的,看起来我使用列表作为本地状态,并在获取数据后对其进行更新,列表完美加载到 tbody 上,但在 handleDelete 内部仍未定义

const [list, setList] = useState([]);

useEffect(async () => {
    fetchData();
}, []);

 async function fetchData() {
    const { data } = await supplier.listSupplier();
    setList(data.data);
}

const confirmDelete = (id) => {
    alertify.confirm(() => {
        handleDelete(id);
    });
};

const handleDelete = async (id) => {
    console.log("list>>", list); //returning undefined
    const originalList = list;
    const list = list.filter((r) => r.id !== id); // throwing Cannot read property 'filter' of undefined
    setState(list);
    try {
        await supplier.deleteSupplier(id);
        alertify.success("Successfully Deleted");
    } catch (ex) {
        if (ex.response && ex.response.status === 404) {
            toastify.error("Already Deleted.");
        }
        setState(originalList);
    }
};

return(
    
     <tbody>
        {list &&
            list.map((row, i) => (
                <tr key={row.id}>
                    <td>
                            <button
                                className="btn btn-danger btn-xs"
                                title="Delete"
                                onClick={() => confirmDelete(row.id)}
                            >
                                <i className="fas fa-trash"></i>
                            </button>
                    </td>
                </tr>
            ))}
    </tbody>

)

在这里,在handleDelete() 上,它的抛出错误throwing Cannot read property 'filter' of undefined 很明显该列表似乎在那里未定义。我该如何解决这个问题?

【问题讨论】:

  • 看看list 是什么会有所帮助。在记录和使用它之后定义一个新的可能无济于事。吊装是真的。
  • 检查您的list 没有被填充的原因。
  • 我们需要看看你在哪里定义列表。
  • 你们能否检查一下问题,我已经更新了。
  • @DaveNewton 可以检查一下问题,我已经更新了代码块

标签: reactjs


【解决方案1】:

看起来像一个命名问题。请检查代码中的注释。

const handleDelete = async (id) => {
    const originalList = list;

//here i don't suggest updating list on this way
//as list is the state and setState is the way to go
//next thing I have changed is that I created newList instead of list again
    const newList = originalList.filter((r) => r.id !== id); 
    //also it looks like you have named setList while defining the state
    setList(newList);
    try {
        await supplier.deleteSupplier(id);
        alertify.success("Successfully Deleted");
    } catch (ex) {
        if (ex.response && ex.response.status === 404) {
            toastify.error("Already Deleted.");
        }
        setList(originalList);
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2019-07-14
    • 2020-01-17
    相关资源
    最近更新 更多