【问题标题】:Delete an Item from Array not Rendering ReactJS Hooks从不渲染 ReactJS Hooks 的数组中删除一个项目
【发布时间】:2020-03-01 13:28:44
【问题描述】:

我正在尝试使用索引从数组中删除一个项目, 我正在将 Props 从父组件传递给子组件以执行此操作,现在我可以看到控制台日志它被删除了,但它没有呈现组件

我已经在 SandBox 中发布了代码,因为这里会很乱

链接:https://codesandbox.io/s/jovial-burnell-qkl7r

【问题讨论】:

标签: reactjs


【解决方案1】:

您正在渲染来自props.listofapi 的数据,但更新数组时,您的更改不会更新,因为您更改了错误的数组。 .splice() 从数组中删除/添加项目,您不必这样做 setArray(...array, temp);setArray(tempArray);

使用 useEffect 将初始数据保存到数组中。

const deleteHandler = id => {
  console.log(id);
  const tempArray = [...array];
  // removes item from tempArray
  tempArray.splice(id, 1); 
  setArray(tempArray);
  console.log("temp array", tempArray);
};

React.useEffect(() => {
  // data from props to array here
  setArray(props.listofapi);
}, [props.listofapi]);

映射数组而不是props.listofapi

<TableBody>
      {array.map((row, index) => (
      ...

Example

【讨论】:

  • 嘿伙计,我猜你忘了添加props.listofapi 作为Effect 依赖项。没有它是行不通的。
【解决方案2】:

组件仅在 state 发生更改时重新渲染,您实际所做的是将 propsparent 传递到 child,这不是 state 值。 因此,您可以尝试以下方式,我们需要先设置本地状态,以便当状态更新时,组件将重新渲染。

只需用以下内容更新代码

  React.useEffect(() =>{
    setArray(props.listofapi)
    //this acts as componentdidmount

  },[]);

  React.useEffect(() =>{
    console.log('state value changed', array)
    // this is the way a call back function is called in the hooks
  },[array]);

我已经更新了snippet

【讨论】:

    【解决方案3】:

    在您的 RenderList 组件中,您需要将状态设置为正在传递的道具

    const RenderList = props => {
      // console.log(props.listofapi);
      const classes = useStyles();
    
    
      const [array, setArray] = React.useState(props.listofapi); // to update the component
    
      const deleteHandler = index=> {
        console.log(id);
        setArray(array.filter((item, i) => i!== index));
      };
    
      return (
        <TableContainer
          component={Paper}
          className={classes.table}
          style={{ align: "center" }}
        >
          <Table
            stickyHeader
            className={classes.container}
            size="small"
            aria-label="a dense table"
          >
            <TableHead>
              <TableRow>
                <TableCell>User ID</TableCell>
                <TableCell>Name</TableCell>
                <TableCell>Use Name</TableCell>
                <TableCell>Email ID</TableCell>
                <TableCell>Edit </TableCell>
                <TableCell>Delete</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {array.map((row, index) => (
                <TableRow key={index}>
                  <TableCell component="th" scope="row">
                    {row.id}
                  </TableCell>
                  <TableCell>{row.name}</TableCell>
                  <TableCell>{row.username}</TableCell>
                  <TableCell>{row.email}</TableCell>
                  <TableCell>
                    <Button variant="contained" size="small" color="primary">
                      Edit Me
                    </Button>
                  </TableCell>
                  <TableCell>
                    <Button
                      variant="contained"
                      size="small"
                      color="primary"
                      onClick={() => deleteHandler(index)}
                    >
                      Delete Me
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      );
    };
    export default RenderList;
    

    【讨论】:

      【解决方案4】:

      您刚刚滥用的问题幸免于难。试试这个:

        const deleteHandler = id => {
          // do your logic on the array that coming from props
          let temp = props.listofapi.splice(id, 1);
          // using spread
          setArray([...array, temp]);
        };
      

      codeSandbox查看您的代码

      编辑:请注意,您正在直接编辑/删除和映射props.listofapi 数组,因此.splice() 方法将更改/删除其现有元素。如果您不想这样,您应该尝试 @Junius L. 解决方案。

      【讨论】:

      • 其实没有,不一定。您仍然可以编辑从 props 传递的数组(请参阅我的沙箱链接),但除非您需要,否则不建议这样做。
      猜你喜欢
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 2017-02-22
      • 2016-12-08
      • 1970-01-01
      • 2018-11-05
      • 2018-04-18
      • 2021-01-22
      相关资源
      最近更新 更多