如何在 React 中使用 .splice() 属性?

伊格纳西奥·加西亚

我是 Reactjs 的新手,在这种情况下,我试图显示操作列表。我只需要显示列表的最后 10 个操作,我正在尝试使用.splice()数组来执行此操作我尝试了很多,但无法使其正常工作。我收到以下错误:

类型错误:列表不可迭代。

知道如何做到这一点吗?

到目前为止,这是我的组件代码:

export default function ListOperations() {
  const dispatch = useDispatch();
  // const list = useSelector((state) => state.operations);
  const [list, setList] = React.useState({});

  React.useEffect(async () => {
    try {
      const response = await axios.get("http://localhost:3000/operation");

      dispatch({
        type: "LIST_OPERATIONS",
        list: response.data,
      });
    } catch (e) {
      swal("Error", e.message, "error");
    }
  }, []);

  const currentListCopy = [...list];

  if (currentListCopy >= 10) {
    currentListCopy.splice(10);
    setList(currentListCopy);
  }

  return (
    <div>
      <div>
        <h2>OPERATIONS HISTORY:</h2>
      </div>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Reason</th>
            <th>Amount</th>
            <th>Date</th>
            <th>Type</th>
          </tr>
        </thead>
        <tbody>
          {list.map((oneOperation) =>
            oneOperation ? (
              <tr key={oneOperation.id}>
                <td>{oneOperation.id}</td>
                <td>{oneOperation.reason}</td>
                <td>{oneOperation.amount}</td>
                <td>{oneOperation.date}</td>
                <td>{oneOperation.type}</td>
              </tr>
            ) : null
          )}
        </tbody>
      </table>
    </div>
  );
}

更新后的版本:

export default function ListOperations(){
    const dispatch = useDispatch();
    const storeList = useSelector((state) => state.operations);
    const [list, setList] = React.useState([]);

    React.useEffect(async () => {
        try{
            const response = await axios.get('http://localhost:3000/operation');

            dispatch({
                type: 'LIST_OPERATIONS',
                list: response.data
            })

            if(Array.isArray(storeList) && storeList.length){
                const currentListCopy = [...storeList];
                if(currentListCopy.length >= 10){
                    currentListCopy.splice(10);
                    setList(currentListCopy);
                }
            }
        }
        catch(e){
            swal("Error", e.message, "error");
        }
    }, [storeList]);
朱奈德·法里亚德

有几个问题会导致错误,而且,如果错误得到修复,获取的结果将不会显示在应用程序中。

第 1 期

const [list, setList] = React.useState({});

在上面的代码中,您将 state 初始化为一个对象,这会导致错误list is not iterable,在下面的代码中,当您尝试使用扩展运算符创建state object.

const currentListCopy = [...list];

使固定

您可以通过将list状态初始化为空数组来解决此问题

const [list, setList] = React.useState({});

第二期

第二个问题是你在useEffect钩子中分派一个动作,但没有从商店获取更新的状态,因为这一行// const list = useSelector((state) => state.operations);被注释掉了。由于您既没有从 store 中获取任何状态,也没有更新本地 state list,即使在 API 调用中从网络返回了一些数据,您也不会看到 map 函数中的任何更改,因为它是空的。

使固定

如果您希望使用 store 中的 state 来更新本地 store,那么您必须取消对此行的注释// const list = useSelector((state) => state.operations) 并将 list 重命名为其他内容。

此外,您还需要将splice代码移动useEffect钩子上,因此,每当list在全局状态中更新时,您的本地状态也会相应地更新。

React.useEffect(() => {
    if (Array.isArray(list) && list.length) { // assuming list is the global state and we need to ensure the list is valid array with some indexes in it.
      const currentListCopy = [...list];
      if(currentListCopy.length >= 10) { // as above answer point out
        currentListCopy.splice(10);
        setList(currentListCopy)
      }
    }
 }, [list]); // added list as a dependency to run the hook on any change in the list

另外,正如上面的回答指出的那样,您应该避免useEffect.

更新

完整的代码

export default function ListOperations() {
  const dispatch = useDispatch();
  const storeList = useSelector((state) => state.operations);
  const [list, setList] = React.useState([]);

  React.useEffect(async () => {
    try {
      const response = await axios.get("http://localhost:3000/operation");

      dispatch({
        type: "LIST_OPERATIONS",
        list: response.data,
      });
    } catch (e) {
      swal("Error", e.message, "error");
    }
  }, []);

  React.useEffect(() => {
    if (Array.isArray(storeList) && storeList.length) {
      const currentListCopy = [...storeList];
      if(currentListCopy.length >= 10) {
        currentListCopy.splice(10);
        setList(currentListCopy)
      }
    }
 }, [storeList]);

  return (
    <div>
      <div>
        <h2>OPERATIONS HISTORY:</h2>
      </div>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Reason</th>
            <th>Amount</th>
            <th>Date</th>
            <th>Type</th>
          </tr>
        </thead>
        <tbody>
          {list.map((oneOperation) =>
            oneOperation ? (
              <tr key={oneOperation.id}>
                <td>{oneOperation.id}</td>
                <td>{oneOperation.reason}</td>
                <td>{oneOperation.amount}</td>
                <td>{oneOperation.date}</td>
                <td>{oneOperation.type}</td>
              </tr>
            ) : null
          )}
        </tbody>
      </table>
    </div>
  );
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章