【问题标题】:How to return to old state after searching table React Hooks搜索表 React Hooks 后如何返回旧状态
【发布时间】:2021-05-27 18:45:36
【问题描述】:

这就是我想要做的:

  1. 通过搜索栏搜索表格并让它返回过滤后的实时更改患者。
  2. 如果搜索栏中有空字符串或用户单击了取消搜索按钮,则在搜索发生之前正常返回所有患者。

问题来了:

搜索结束后,我无法恢复旧状态。

这是我的代码:

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>

【问题讨论】:

    标签: reactjs react-hooks material-ui react-functional-component


    【解决方案1】:

    不要在每次搜索时更改患者状态,而是仅更改搜索值状态,并且内部渲染函数使用返回过滤患者的函数

    类似

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

    【讨论】:

      【解决方案2】:

      在设置状态下,您可以访问之前的状态,例如,典型的计数器示例如下:

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

      实际上,鼓励使用函数调用 setState 以在后续调用中保持当前状态值,而不是覆盖之前的值。例如,如果您设置了两次计数器,则只会发生 +1:

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

      因为您将两次都对原始状态值执行++。 也就是说,我会使用 set state 和一个函数来保持之前的状态,以便以后可以使用它,如下所示:

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

      (未调试的代码) 这样一来,以前的状态将在 const previousState 中,以防您需要将其设置回来。

      【讨论】:

      • 没有按预期工作,因为搜索功能在每次按键时都会运行,因此我们保留的先前状态被覆盖。
      • 我通过有条件地检查previousState的长度是否等于0来修复它,这样它就可以完美地工作。感谢您的回复。
      • 然后将结果保存在不同的const 变量中。一个用于搜索结果,一个用于之前的状态。
      猜你喜欢
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多