简体   繁体   English

搜索表 React Hooks 后如何返回旧的 state

[英]How to return to old state after searching table React Hooks

here's what I'm trying to do:这就是我想要做的事情:

  1. Search a table through the search bar and have it return the filtered patients on live changes.通过搜索栏搜索表格,并让它返回过滤后的实时更改患者。
  2. Return all patients as normal before the search happened if there's an empty string in the search bar or if the user clicked cancelSearch button.如果搜索栏中有空字符串或用户单击取消搜索按钮,则在搜索发生之前正常返回所有患者。

Here's the issue:这是问题:

I cannot get the old state back once the search is over.搜索结束后,我无法找回旧的 state。

Here's my code:这是我的代码:

const [patients, setPatients] = useState([

    ])  

 // GET/Fetch all patients, listener for patients

useEffect(() => {
    fetch('api/patients')
    .then(response => response.json())
    .then(json => setPatients(json))

}, [])

const [searched, setSearched] = React.useState("")


  const requestSearch = (searchedVal) => {
    const filteredPatients = patients.filter((patient) => {
      return patient.fullName.toLowerCase().includes(searchedVal.toLowerCase());
    });
    setPatients(filteredPatients);
  };


  const cancelSearch = () => {
    setSearched("");
    requestSearch(searched);
  };

<SearchBar
    value={searched}
    onChange={(searchVal) => requestSearch(searchVal)}
    onCancelSearch={() => cancelSearch()}
  />
      <TableContainer component={Paper} style={{overflow: "hidden"}}>
      <Table className={classes.table} aria-label="simple table">
        <TableHead>
          <TableRow>
            <TableCell><strong>Name</strong></TableCell>
            <TableCell align="right"><strong>Age</strong></TableCell>
            <TableCell align="right"><strong>Condition</strong></TableCell>
            <TableCell align="right"><strong>Diagnosis</strong></TableCell>
            <TableCell align="right"><strong>Supervising Doctor</strong></TableCell>
            <TableCell align="right"><strong>Status</strong></TableCell>
            <TableCell align="center"><strong>Action</strong></TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {patients.map((patient) => (
                        <>
          {patient.status === "Active" &&         
        <Slide direction="up" in={patients} mountOnEnter unmountOnExit>
        <TableRow key={patient._id}>
              <TableCell>{patient.fullName}</TableCell>
              <TableCell align="right">{patient.age}</TableCell>
              <TableCell align="right">{patient.condition}</TableCell>
              <TableCell align="right">{patient.diagnosis}</TableCell>
              <TableCell align="right">{patient.supervisor}</TableCell>
              <TableCell align="right">{patient.status}</TableCell>
              <TableCell align="center">
                  <Tooltip title="Details">
                        <IconButton aria-label="details" component={Link} to={`/patients/${patient._id}`}>
                            <PersonPinIcon />
                         </IconButton>
                        </Tooltip> 
                        <Tooltip title="Delete">
                          <IconButton aria-label="delete" onClick={()=>deletePatient(patient._id)}>
                            <DeleteIcon />
                          </IconButton>
                         </Tooltip> 
              </TableCell>
            </TableRow>
            </Slide>
            }
            </>
          ))}
        </TableBody>
      </Table>
    </TableContainer>

In the set state you can access the previous state, for example, for the typical counter example like this:在集合 state 中,您可以访问以前的 state,例如,对于像这样的典型反例:

setPatients((prevCounter) => { prevCounter++ });

Actually to call setState with a function is encouraged to maintain the current state value in successive calls and not overwrite the previous.实际上,鼓励使用 function 调用 setState 以在连续调用中保持当前 state 值,而不是覆盖以前的值。 For example if you had set counter twice, only +1 will take place:例如,如果您设置了两次计数器,则只会发生 +1:

setPatients(prevCounter++);
setPatients(prevCounter++);

Because you would be doing the ++ both times to the original state value.因为您将对原始 state 值执行++两次。 That said, I would use the set state with a function to keep the previous state, so that it can be used afterwards, like this:也就是说,我会使用集合 state 和 function 来保留之前的 state,以便之后可以使用它,如下所示:

const previousState;
setPatients((prevState) => { 
    previousState = prevState;
    return filteredPatients 
});

(Not debugged code) That way, previous state would be in the const previousState in case you need to set that back. (未调试代码)这样,以前的 state 将处于const previousState中,以防您需要将其设置回来。

Instead of changing the patients state everytime you search change only the searched value state and inside render function use a function that returns the filtered patients Instead of changing the patients state everytime you search change only the searched value state and inside render function use a function that returns the filtered patients

something like就像是

<tablebody>
this.somefilterfunction().map ....
</tablebody>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM